Django Rest Framework实现了多对多的关系

时间:2015-12-23 18:47:59

标签: python django rest django-rest-framework django-serializer

我希望实现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视图,但它没有显示电影名称,但是我无法看到人员列表。我该如何正确地做到这一点?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

如果您使用多对多关系,请确保明确声明该字段,如下所示:

class WidgetSerializer(serializers.HyperlinkedModelSerializer):
    
    parts__part = serializers.CharField()
    

    class Meta:
        model = Widget
        fields = ['date', 'url', 'type','parts__part']