Search code examples
pythondjangorestdjango-rest-frameworkdjango-serializer

Django Rest Framework implementing many to many relationship


I want implement a many to many relationship such that one person can join multiple social clubs and one social club can have multiple members. This is how far I've got but this doesn't display the movie details and serialization gives me an error -
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'),
])

on my local server, I get the clubs list which navigates me to clubdetail view,but it doesn't show the movie names or, but I can't see the person list. How do I do this correctly?


Solution

  • You have a number of issues in your code here. Namely:

    • ClubSerializer.Meta.fields - person should be person_set
    • PersonSerializer - clubs should be clubs = ClubSerializer(many=True)
    • ClubDetail.serializer_class - ClubSerializer should be PersonSerializer
    • ClubDetail - queryset should be persons = Person.objects.filter(clubs=club)

    If you fix the above, you should be able to navigate to ClubDetail and see a list of club members.