通过使用带有嵌套序列化程序的Django Rest Framework,我一直在通过其他属性传递问题。
我创建了一个文档模型,该模型具有ForeignKey 所有者 /创建者关系,以及其他几个与ForeignKey相关的模型。其他一些模型也有一个所有者 /创建者ForeignKey关联。
class Document(models.Model):
owner = models.ForeignKey('auth.User',related_name='document')
candidate = models.ForeignKey(
Candidate,
on_delete=models.CASCADE,
blank=True,
null=True,
)
class Candidate(models.Model):
owner = models.ForeignKey('auth.User', related_name='candidates')
first_name = models.CharField(max_length=30, blank=True, null=True)
使用嵌套序列化程序和自定义create()
方法保存文档模型时,我可以向下传递所有字段,但嵌套模型似乎不是能够拿起所有者字段,无论我如何传入它。单独创建一个候选人是好的。
class CandidateSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Candidate
fields = (
'pk',
'first_name',
'owner',
)
class DocumentSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
candidate = CandidateSerializer(required=True)
class Meta:
model = Document
fields = (
'owner',
'candidate',
)
def create(self, validated_data):
candidate_data = validated_data.pop('candidate')
document = Document.objects.create(**validated_data)
Candidate.objects.create(**candidate_data)
将 DocumentSerializer 设置为这样,我在尝试使用嵌套字段对文档进行POST时会出现这样的错误。
IntegrityError: NOT NULL constraint failed: dossier_candidate.owner_id
当我修改DocumentSerializer.create()
方法以尝试接收所有者时,owner = serializers.ReadOnlyField(source='owner.username')
现在似乎已超出范围,即使它应该在该类之下。
即,
当我尝试使用
创建Candidate对象时Candidate.objects.create(owner, **candidate_data)
我收到此错误:
NameError at /rest/documents/
global name 'owner' is not defined
当我尝试这个时
Candidate.objects.create(self.owner, **candidate_data)
我收到此错误:
AttributeError: 'DocumentSerializer' object has no attribute 'owner'
确保嵌套的Candidate对象能够成功创建并获取所有者字段的正确方法是什么?