Have two models:
class Topic(Base):
name = models.CharField(max_length=100, unique=True)
display_name = models.CharField(max_length=100)
class SubTopic(Base):
name = models.CharField(max_length=100, unique=True)
display_name = models.CharField(max_length=100)
topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
and have two serializers:
class SubTopicSerializer(serializers.ModelSerializer):
class Meta:
model = SubTopic
fields = ('topic', 'name', 'display_name')
class TopicSerializer(serializers.ModelSerializer):
sub_topics = SubTopicSerializer(many=True, read_only=True)
class Meta:
model = Topic
fields = ('id', 'display_name', 'sub_topics')
the subtopics are not populating in the response.
I was missing the related_name parameter on the ForeignKey.
class SubTopic(Base):
name = models.CharField(max_length=100, unique=True)
display_name = models.CharField(max_length=100)
topic = models.ForeignKey(ContextualTopic, related_name="sub_topics", on_delete=models.CASCADE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.