django关联外键
程序员文章站
2022-04-21 10:11:53
...
使用django进行关联外键
- 当两个属性关联一个外键的时候,需要添加一个related_name字段,
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
phone = models.CharField(verbose_name='手机号',max_length=11)
fengsi = models.ForeignKey(to='self',null=True,blank=True,on_delete=models.CASCADE,related_name='粉丝')
guanzhu = models.ForeignKey(to='self',null=True,blank=True,on_delete=models.CASCADE,related_name='关注')
class Meta:
verbose_name = '用户'
verbose_name_plural = verbose_name
def __str__(self):
return self.username
- 如果没有添加related_name就会报这个错
app01d.User.guanzhu: (fields.E304) Reverse accessor for 'User.guanzhu' *es with reverse accessor for 'User.fengsi'.
HINT: Add or change a related_name argument to the definition for 'User.guanzhu' or 'User.fengsi'.