Enes
Enes

Reputation: 341

Django rest one-to-many Got AttributeError

Error

Got AttributeError when attempting to get a value for field participant_set on serializer MatchSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Match instance. Original exception text was: 'Match' object has no attribute 'participant_set'.

Models.py

class TournamentTeam(models.Model):
    tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True)
    team = models.ForeignKey(TeamPlayer, on_delete=models.SET_NULL, null=True)

class Match(models.Model):
    name = models.TextField(blank=False, null=False)
    participant = models.ManyToManyField(TournamentTeam, through='MatchParticipant')

class MatchParticipant(models.Model):
    match = models.ForeignKey(Match, on_delete=models.SET_NULL, null=True, blank=True)
    team = models.ForeignKey(TournamentTeam, on_delete=models.SET_NULL, null=True, blank=True)
    score = models.CharField(max_length=255, null=True, blank=True)

Serializers.py

class MatchParticipantSerializer(serializers.ModelSerializer):

    class Meta:
        model = MatchParticipant
        fields = '__all__'


class MatchSerializer(serializers.ModelSerializer):
    participant_set=MatchParticipantSerializer(many=True)

    class Meta:
        model = Match
        fields = ('name','participant_set')

Views.py

class MatchAPIView(ListAPIView):
    queryset = Match.objects.all()
    serializer_class = MatchSerializer

Upvotes: 0

Views: 123

Answers (1)

dirkgroten
dirkgroten

Reputation: 20692

With your model definitions, your Match model has the following attributes:

  • participant is the query manager to query all the TournamentTeams linked to this Match (using plural is advised when defining an m2m field, so participants would be better). E.g. match.participant.all()
  • matchparticipant_set is the query manager to query the "through" model instances, of type MatchParticipant. E.g. match.matchparticipant_set.all().

In the reverse direction, since you haven't defined related_name on the participant field, you have:

  • TournamentTeam.match_set for the query manager to fetch the related Match instances
  • TournamentTeam.matchparticipant_set for the MatchParticipant instances.

Upvotes: 1

Related Questions