ARST打卡第102周[102/521]

Algorithm

LeetCode/31_下一个排列

Review

TED演讲:努力之外,运气也很重要!

敬重那些本来应该和我们一样成功但是没有我们幸运的人

Tips

model_form的官方文档

Share

想了很多天,想到使用model添加很多备用的Person数据,如下

1
2
3
4
5
6
7
8
9
10
11
12
class Project(models.Model):
name = models.CharField(max_length=100)
video = models.ForeignKey(Video, on_delete=models.CASCADE, null=True)
person = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
person_1 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
person_2 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
person_3 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
person_4 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
person_5 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL)
# 结果一开始容许为空 null=True
result = models.ForeignKey(Result, null=True, blank=True, on_delete=models.SET_NULL)

可是报错,不能这样搞

1
2
3
4
5
6
7
8
9
[root@lm videoproject]# python manage.py makemigrations
SystemCheckError: System check identified some issues:

ERRORS:
cut.Project.person: (fields.E304) Reverse accessor for 'Project.person' clashes with reverse accessor for 'Project.person_1'.
HINT: Add or change a related_name argument to the definition for 'Project.person' or 'Project.person_1'.
cut.Project.person: (fields.E304) Reverse accessor for 'Project.person' clashes with reverse accessor for 'Project.person_2'.
HINT: Add or change a related_name argument to the definition for 'Project.person' or 'Project.person_2'.
cut.Project.person: (fields.E304) Reverse accessor for 'Project.person' clashes with reverse accessor for 'Project.person_3'.

解决方案(如上所述,添加一个related_name):

原理解释:
如果不加related_name,那么Project有多个Person外键,当某一个Person反向查找遍历的时候,都是查找person_set,由于两个反向关系使用相同的名称,因此将导致歧义。

1
2
3
4
5
6
7
8
9
10
11
class Project(models.Model):
name = models.CharField(max_length=100)
video = models.ForeignKey(Video, on_delete=models.CASCADE, null=True)
person = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_0')
person_1 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_1')
person_2 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_2')
person_3 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_3')
person_4 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_4')
person_5 = models.ForeignKey(Person, null=True, blank=True, on_delete=models.SET_NULL, related_name='person_5')
# 结果一开始容许为空 null=True
result = models.ForeignKey(Result, null=True, blank=True, on_delete=models.SET_NULL)

参考

https://stackoverflow.com/questions/58788480/python-error-fields-e304-reverse-accessor-for-field-clashes-with-reverse-acc

https://blog.csdn.net/m0_37156322/article/details/86691765