Search code examples
djangomanytomanyfielddjango-tests

AttributeError: Class1 object has no attribute 'class2_set' with ManyToMany Field Django


Model :

class Groupe(models.Model):
    name = models.CharField(max_length=255)
    autoAddingMail = models.CharField(max_length=255,null=True,blank=True)
    association = models.ForeignKey(
        User,
        limit_choices_to={'role': 'ASSOCIATION'},
        null=False,
        on_delete=models.CASCADE,
        related_name='association'
    )
    students = models.ManyToManyField(
        User,
        limit_choices_to={'role': 'STUDENT'},
        related_name='students'
    )
    events = models.ManyToManyField(
        Event
    )

    class Meta:
        unique_together = ("name","association")

    REQUIRED_FIELDS = ['name','association']

    def __str__(self):
        """ Return string representation of our user """
        return self.name

Unit test :

groupe = event.groupe_set.get(name="name",association=association) <= works fine

groupe = student.groupe_set.get(name="name",association=association) <= doesn't work

The error : AttributeError: 'User' object has no attribute 'groupe_set'

I don't get why student doesn't have the attribute groupe_set but event have it

I have read the documentation about ManyToMany Fields but I didn't find answers.


Solution

  • Instead of

    groupe = student.groupe_set.get(name="name",association=association)

    I had to use :

    groupe = student.students.get(name="name",association=association)

    Because of the related_name. Thanks to @iklinac for his comment.