欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

django关联外键

程序员文章站 2022-04-21 10:11:53
...

使用django进行关联外键

  1. 当两个属性关联一个外键的时候,需要添加一个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
  1. 如果没有添加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'.
相关标签: django django