gpt4 book ai didi

django ManyToMany 通过帮助

转载 作者:行者123 更新时间:2023-12-04 15:04:57 26 4
gpt4 key购买 nike

嘿,我有一个关于人际关系的问题。

我希望用户有友谊。所以一个用户可以成为另一个用户的 friend 。我假设我需要通过 Friendship 表使用 ManyToManyField。但我无法让它工作。有任何想法吗?

这是我的模型。

class User(models.Model):
username = models.CharField(max_length=999)
password = models.CharField(max_length=999)
created_on = models.DateField(auto_now = False, auto_now_add = True)
updated_on = models.DateField(auto_now = True, auto_now_add = False)
friends = models.ManyToManyField('self')
pendingFriends = models.ManyToManyField('self', through='PendingFriendship', symmetrical=False, related_name='friend_requested')

class PendingFriendship(models.Model):
user = models.ForeignKey('User', related_name='user')
requested_friend = models.ForeignKey('User', related_name='requested_friend')
created_on = models.DateField(auto_now = False, auto_now_add = True)
updated_on = models.DateField(auto_now = True, auto_now_add = False)

谢谢

最佳答案

多对多字段在 documentation 中描述.做就是了:

class User(models.Model):
username = models.CharField(max_length=999)
password = models.CharField(max_length=999)
created_on = models.DateField(auto_now = False, auto_now_add = True)
updated_on = models.DateField(auto_now = True, auto_now_add = False)
friends = models.ManyToManyField('self')
您只需使用 through如果您想向关系添加额外的字段。在 this section 中描述了所有可能性的另一种描述。 .
当您命名模型用户时,我假设您没有使用内置身份验证框架。但是如果你使用它,你不必自己实现认证,所以考虑一下。
更新:
你读过我链接的部分吗?那里是这样描述的:

There are a few restrictions on the intermediate model:

  • Your intermediate model must contain one - and only one - foreign key to the target model (this would be Person in our example). If you have more than one foreign key, a validation error will be raised.
  • Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.
  • The only exception to this is a model which has a many-to-many relationship to itself, through an intermediary model. In this case, two foreign keys to the same model are permitted, but they will be treated as the two (different) sides of the many-to-many relation.
  • When defining a many-to-many relationship from a model to itself, using an intermediary model, you must use symmetrical=False (see the model field reference).

关于django ManyToMany 通过帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2446753/

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