【问题标题】:Calling an instance of same class inside class在类内调用同一类的实例
【发布时间】:2015-12-04 20:36:07
【问题描述】:

我在 Django 中有一个名为 Student 的模型,我希望一个变量 student 成为与他们成为朋友的其他学生。例如:

Tim.friends_set.all() = 吉姆、鲍勃、山姆

我的 _____ 在这段代码中是什么?有没有办法在不创建新模型的情况下做到这一点?

class Student(models.Model):
    name = models.CharField(max_length=128, unique=True)
    friends = models.________(Student, blank = True)

我想象如果我创建一个新模型,它会是这样的:

class friends(models.Model):
    student = models.ForeignKey(Student)
    friends = models.models.ManyToManyField(Student, blank = True)

【问题讨论】:

  • 你试过使用 ForeignKey 吗?

标签: python sql django model foreign-key-relationship


【解决方案1】:

使用ManyToManyField 和参数'self'

class Student(models.Model):
  name = models.CharField(max_length=128, unique=True)
  friends = models.ManyToManyField('self', blank = True)

您不妨考虑一下关系是否为symmetrical

【讨论】:

  • 对称是基于最近邻的,因此它们可能是不对称的实例。不过值得怀疑。当我用 'self' 调用它时,它说: assert isinstance(to, Six.string_types), "%s(%r) is invalid. ManyToManyField 的第一个参数必须是模型、模型名称或字符串 % r" % (self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT) AssertionError: ManyToManyField() 无效。 ManyToManyField 的第一个参数必须是模型、模型名称或字符串 u'self'
  • @Rob 默认情况下关系是对称的 - 意思是如果 A 是 B 的朋友,那么 B 也是 A 的朋友。
  • 你在哪里引用Student?注意ManyToMany 字段的参数是'self',而不是Student
  • 我从您写的内容中复制并粘贴了它,所以我不确定它是在我的代码中的其他地方还是什么。
  • 我上面写的示例是有效的——你可以使用它。请将您的新代码添加到问题中,或者如果您仍有问题,请提出新问题。您的错误消息表明您对ManyToManyField 的第一个参数不正确(听起来您正在做类似models.ManyToManyField(many_to_many_field_instance) 的事情)
猜你喜欢
  • 2013-01-13
  • 2018-07-17
  • 2012-05-07
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多