Skip to content Skip to sidebar Skip to footer

Django Rest-farmework Nested Relationships

Using django rest-farmework to implement the API, there is a problem in the nested relationship here. The content associated with the foreign key can not be displayed, the specific

Solution 1:

Thanks to Klaus D's comments, the problem is solved. We can add related_name = 'source' in the models.py like this:

class Source(models.Model):
    name = models.CharField(max_length=50)
    rss_link = models.URLField()
    amount = models.IntegerField()
    # ForeignKey
    category = models.ForeignKey(Category,related_name = 'source')

If you do not add related_name in the foreignkey, the default is "source_set".

So, we can also solve the problem like this:

#serializers.py
class CategorySerializers(serializers.ModelSerializer):
    source_set = SourceSerializers(many=True, read_only=True)

    class Meta:
        model = Category
        fields = ("id","name","amount","source_set")

Post a Comment for "Django Rest-farmework Nested Relationships"