Django可以建立指向自己model的外键吗?,djangomodel,如题,试着用django


如题,试着用django系统做一个微博系统,在建立user model时使用的是OneToOne的方式扩展django.contrib.auth.admin的User,但出了点问题,想实现微博上关注和粉丝的功能,这样写报错

class weiboUser(models.Model):    user = models.OneToOneField(User)    fans = models.ForeignKey(weiboUser,related_name="fans")    focus  = models.ForeignKey(weiboUser,related_name="focus")

所以想问一下如何在model下建立指向自身model的外键?谢谢。

补充,参照了官方文档,做了以下修改,虽然不报错了,但无法同步数据库,求高人继续指导。

class weiboUser(models.Model):    user = models.OneToOneField(User)    fans = models.ManyToManyField('self',symmetrical=False)    focus  = models.ManyToManyField('self',symmetrical=False)

目测楼主不懂数据库

需要建立一个抽象类为父类,用代码说话:

class AbstractNavi(models.Model):      parent = models.ForeignKey('self',blank=True, null=True, related_name='child')      class Meta:          abstract = True      class Navi(AbstractNavi):      """     Navi has four type: goods, news, page and custom     """      STYLE_CHOICES = (          ('goods', 'goods'),          ('news', 'news'),          ('page', 'page'),          ('custom', 'custom'),      )      name = models.SlugField()      #parent = models.ForeignKey('self', null=True, blank=True, related_name='child')      style = models.SlugField(choices=STYLE_CHOICES)      url = models.CharField(max_length=100, default='#')      sort = models.IntegerField(default=1)      is_display = models.BooleanField(default=True)      def __unicode__(self):          return self.name  

编橙之家文章,

评论关闭