gpt4 book ai didi

python - Django 中的递归关系不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 12:40:33 25 4
gpt4 key购买 nike

在官方文档中写着https://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey

To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self').

例如我使用下一个模型:

class MediaGroup:
name = models.CharField(max_length=200)
parent = models.ForeignKey('self', blank=True, related_name="children")

当我运行 syncdb 时,它会抛出下一个异常:

File "/usr/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 939, in __init__
assert isinstance(to, basestring), "%s(%r) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string %r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
AssertionError: ForeignKey(<class webpanel.models.MediaGroup at 0x225ca10>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self'

最佳答案

你错过了(models.Model):

class MediaGroup(models.Model):

关于python - Django 中的递归关系不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18125793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com