如何在Django REST框架中为多对多相关对象序列化器创建反向字段?
**Models**
class Tag(models.Model):
name = models.CharField(max_length=500, blank=True)
class Event(models.Model):
max_attendee = models.IntegerField(default=0)
description = models.TextField(blank=True)
tags = models.ManyToManyField(Tag, related_name='events_tags')
** Serializers **
class EventSerializer(serializers.HyperlinkedModelSerializer):
tags = serializers.HyperlinkedRelatedField(many=True, view_name='tag-detail')
class Meta:
model = Event
fields = ('id', 'location', 'location_name', 'date', 'max_attendee', 'description', 'image', 'created_by', 'tags')
class TagSerializer(serializers.HyperlinkedModelSerializer):
events = serializers.HyperlinkedRelatedField(many=True, view_name='event-detail')
class Meta:
model = Tag
fields = ('name',)
由于Tags模型中没有events
字段,因此无法显示与标记相关的事件。但是,反向执行很好,因为事件模型中设置了多对多关系。
答案 0 :(得分:0)
您是否尝试过使用该字段的相关名称?
class TagSerializer(serializers.HyperlinkedModelSerializer):
events_tags = serializers.HyperlinkedRelatedField(many=True, view_name='event-detail')
class Meta:
model = Tag
fields = ('name', 'events_tags',)
答案 1 :(得分:0)
尝试更改此内容:
events = serializers.HyperlinkedRelatedField(many=True, view_name='event-detail')
到此:
events_tags = serializers.RelatedField()