AttributeError: Class1 object has no attribute 'class2_set' with ManyToMany Field Django
AttributeError: Class1 object has no attribute 'class2_set' with ManyToMany Field Django
型号:
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
单元测试:
groupe = event.groupe_set.get(name="name",association=association)
<= 工作正常
groupe = student.groupe_set.get(name="name",association=association)
<= 无效
错误:
AttributeError: 'User' object has no attribute 'groupe_set'
我不明白为什么学生没有属性 groupe_set 但活动有
我已阅读有关 ManyToMany 字段的文档,但没有找到答案。
而不是
groupe = student.groupe_set.get(name="name",association=association)
我不得不使用:
groupe = student.students.get(name="name",association=association)
因为related_name。
感谢@iklinac 的评论。
型号:
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
单元测试:
groupe = event.groupe_set.get(name="name",association=association)
<= 工作正常
groupe = student.groupe_set.get(name="name",association=association)
<= 无效
错误:
AttributeError: 'User' object has no attribute 'groupe_set'
我不明白为什么学生没有属性 groupe_set 但活动有
我已阅读有关 ManyToMany 字段的文档,但没有找到答案。
而不是
groupe = student.groupe_set.get(name="name",association=association)
我不得不使用:
groupe = student.students.get(name="name",association=association)
因为related_name。 感谢@iklinac 的评论。