我想实现一种many to many关系,这样一个人可以加入多个社交俱乐部,而一个社交俱乐部可以有多个成员。这是我所走的路,但是没有显示电影详细信息,序列化给我一个错误-
Original exception text was: 'ManyRelatedManager' object has no attribute 'club_name'.

models.py

class Club(models.Model):
  club_name = models.CharField(default='',blank=False,max_length=100)

class Person(models.Model):
  person_name = models.CharField(default='',blank=False,max_length=200)
  clubs = models.ManyToManyField(Club)


serializers.py

class ClubSerializer(serializers.ModelSerializer):
  class Meta:
    model = Club
    fields = ('url','id','club_name','person')

class PersonSerializer(serializers.ModelSerializer):
  clubs = ClubSerializer()
  class Meta:
    model = Person
    fields = ('url','id','person_name','clubs')


views.py

class ClubDetail(generics.ListCreateAPIView):
serializer_class = ClubSerializer

  def get_queryset(self):
    club = Clubs.objects.get(pk=self.kwargs.get('pk',None))
    persons = Person.objects.filter(club=club)
    return persons

class ClubList(generics.ListCreateAPIView):
  queryset = Club.objects.all()
  serializer_class = ClubSerializer


class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
  serializer_class = PersonSerializer


def get_object(self):
  person_id = self.kwargs.get('pk',None)
  return Person.objects.get(pk=person_id)


urls.py

urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^clubs/$',
views.ClubList.as_view(),
name='club-list'),
url(r'^clubs/(?P<pk>[0-9]+)/persons/$',
views.ClubDetail.as_view(),
name='club-detail'),
url(r'^person/(?P<pk>[0-9]+)/$',
views.PersonDetail.as_view(),
name='person-detail'),
])


在我的本地服务器上,我得到了俱乐部列表,该列表将我导航到clubdetail视图,但它不显示电影名称,或者,但我看不到人员列表。如何正确执行此操作?

最佳答案

您的代码中存在许多问题。即:


ClubSerializer.Meta.fields-人员应为person_set
PersonSerializer-俱乐部应为clubs = ClubSerializer(many=True)
ClubDetail.serializer_class-ClubSerializer应该是PersonSerializer
ClubDetail-queryset应该为persons = Person.objects.filter(clubs=club)


如果您解决了上述问题,则应该可以导航到ClubDetail并查看俱乐部成员列表。

关于python - Django Rest Framework实现多对多关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34441899/

10-08 22:56