我有2个与OneToOne相关的模型和模型是FK到第2个模型
models.py
class Legal(TimeStampedModel):
name = models.CharField('Name', max_length=255, blank=True)
class LegalCard(TimeStampedModel):
legal = models.OneToOneField('Legal', related_name='legal_card', on_delete=models.CASCADE)
branch = models.ForeignKey('Branch', related_name='branch', null=True)
post_address = models.CharField('Post address', max_length=255, blank=True)
class Branch(TimeStampedModel):
name = models.CharField('Name',max_length=511)
code = models.CharField('Code', max_length=6)
使用DRF我使它们表现为单一模型,因此我可以创建或更新两者:
serializer.py
class LegalSerializer(serializers.ModelSerializer):
branch = serializers.IntegerField(source='legal_card.branch', allow_null=True, required=False)
post_address = serializers.CharField(source='legal_card.post_address', allow_blank=True, required=False)
class Meta:
model = Legal
fields = ('id',
'name',
'branch',
'post_address',
)
depth = 2
def create(self, validated_data):
legal_card_data = validated_data.pop('legal_card', None)
legal = super(LegalSerializer, self).create(validated_data)
self.update_or_create_legal_card(legal, legal_card_data)
return legal
def update(self, instance, validated_data):
legal_card_data = validated_data.pop('legal_card', None)
self.update_or_create_legal_card(instance, legal_card_data)
return super(LegalSerializer, self).update(instance, validated_data)
def update_or_create_legal_card(self, legal, legal_card_data):
LegalCard.objects.update_or_create(legal=legal, defaults=legal_card_data)
views.py
class LegalDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = Legal.objects.all()
serializer_class = LegalSerializer
我试图通过将FK作为整数发送来保存它(我只想发布分支的id),但是我收到错误
ValueError: Cannot assign "2": "LegalCard.branch" must be a "Branch" instance.
有没有办法只传递分支的ID?
谢谢
答案 0 :(得分:1)
在Django中,如果只需要FK值,则可以使用已经存在的对象上的FK值,而不是获取相关对象。 假设您有一个ID为&的法律和分支对象为1.然后您可以通过以下方式保存LegalCard对象:
LegalCard(legal_id=1,branch_id=1,post_address="Istanbul Street No:1")
答案 1 :(得分:0)
只需使用legal_card.branch_id而不是legal_card.branch来获取id,而不是相关对象。 而深度= 1