Another day another Django Rest Framework error.
It is a short solution yet the one that took some time to get to.
If you you need values of your ForeignKey, method or property, make it a @property and use this tried and true solution.
For models.py:
class Reply(models.Model):
quote = models.ForeignKeyField('self', on_delete=models.CASCADE)
I want the following serializer to work:
class Reply_serial(serializers.ModelSerializer):
class Meta:
model = Reply
fields = [
'id',
'quote_id'
]
Just like that you in case you don’t have quote value, in response there will be:
"quote_id": null
But it is not exactly very friendly. It would be preferable to have 0 instead of null. For that you may want to make a method, but it won’t work very well. So, make a property. In models.py:
class Reply(models.Model):
quote = models.ForeignKeyField('self', on_delete=models.CASCADE)
@property
def get_pk(self):
return self.quote.pk if self.quote else 0
And in your serializer:
class Reply_serial(serializers.ModelSerializer):
quote_id = serializers.ReadOnlyField(source='get_pk')
class Meta:
model = Reply
fields = [
'id',
'quote_id'
]
And voila!
"quote_id": 0
Haha, I think you are very funny based on images on your website
LikeLike
oh, thank you!
LikeLike