我目前对如何最好地在自定义序列化程序验证器方法中引用 ForeignKey 字段的实例有点概念上的头痛......
对系统进行概述。我有以下“ Candidate
”模型,这个问题的重要字段是user
, job
* 和status
字段。
from model_utils.fields import MonitorField, StatusField
from model_utils import Choices
class Candidate(models.Model):
class Meta:
...
STATUS = Choices(
'matched',
'approached',
'invite_rejected',
'invite_accepted',
'reviewed',
'interview_scheduled',
'hired',
'rejected'
)
user = models.ForeignKey('users.User', on_delete=models.CASCADE)
job = models.ForeignKey('jobs.Job', related_name='candidates', on_delete=models.CASCADE)
...
status = StatusField(default='matched')
...
def save(self, *args, **kwargs):
super(Candidate, self).save(*args, **kwargs)
的status
字段Candidate
只能根据他们是谁以及他们试图将状态更新到什么来“更新”为给定值。实际上,我在序列化程序中概述的逻辑如下:
from rest_framework import serializers
from .candidates.models import Candidate
class CandidateSerializer(serializers.ModelSerializer):
class Meta:
model = Candidate
fields = '__all__'
def validate_status(self, value):
user = self.context['request'].user
if user.is_anonymous:
raise serializers.ValidationError("The requester must be logged in to make a change to the status field")
# Ensure status value is in valid list of statuses
if value not in [
'matched',
'approached',
'invite_rejected',
'invite_accepted',
'reviewed',
'interview_scheduled',
'hired',
'rejected'
]:
raise serializers.ValidationError("The value provided does not match the prefedined status list")
# Only the candidate owner can update to certain statuses?
if value in [
'invite_rejected',
'invite_accepted',
]:
if not self.user == user:
raise serializers.ValidationError("You don't have the correct permission to update the status")
if value in [
'matched',
'approached',
'reviewed',
'interview_scheduled',
'hired',
'rejected'
]:
if user.is_anonymous or not self.job.organisation.is_admin(user) or not self.job.organisation.is_member(user):
raise serializers.ValidationError("You don't have the correct permission to update the status")
return value
也就是说,我可以从序列化user
器的.Candidate
self.context['request'].user
我也在检查这user
是否是一开始,而不是匿名的。
我想要访问的是job
上述序列化程序的字段。
我在想job
序列化器的“”属性...可以通过self.job
.
但是,我认为这将返回Job
实例的主键。
所以...我无法访问organisation
self.job 字段上的属性,因为它在技术上不是Job
模型的一个实例:
user = self.context['request'].user
...
if not self.job.organisation.is_admin(user) or not self.job.organisation.is_member(user):
raise serializers.ValidationError("You don't have the correct permission to update the status")
所以,我的问题是,我应该如何正确引用与我试图引用的Job
实例相关联的实例?Candidate
* NB值得注意的是,“ job
”字段本身引用了一个“ Job
”模型,而此 Job 模型又具有一个组织字段,该字段链接到django-organizations
包中概述的组织(参考此处:https ://github.com/ bennylope/django-organizations/如果需要)