【问题标题】:Django: friendship relation between different modelsDjango:不同模型之间的友谊关系
【发布时间】:2016-11-30 18:29:24
【问题描述】:

我正在尝试使用 django-friendship 包在我的项目中建立友谊关系。问题是我要在我的用户模型和我自己的称为组织的模型之间建立关系。但是当我尝试这样做时,事实证明 django-friendship 仅支持相同类型的两个对象之间的关系(例如 User-User 类型)。我什至尝试覆盖 django-friendship 中的现有模型以更改方法但没有任何成功。目前,我正处于将好友请求从用户发送到组织的阶段,但我需要接受它,这就是我挣扎的地方。

friendship/models.py

class FriendshipRequest(models.Model):
    """ Model to represent friendship requests """
    from_user = models.ForeignKey(user_model, related_name='organisation_requests_sent')
    to_user = models.ForeignKey(organisation_model, related_name='organisation_requests_received')

    def accept(self):
        """ Accept this friendship request """
        relation1 = Friend.objects.create(
            from_user=self.from_user,
            to_user=self.to_user
        )

        relation2 = Friend.objects.create(
            from_user=self.to_user,
            to_user=self.from_user
        )

        friendship_request_accepted.send(
            sender=self,
            from_user=self.from_user,
            to_user=self.to_user
        )

class Friend(models.Model):
    """ Model to represent Friendships """
    to_user = models.ForeignKey(user_model, related_name='organisations')
    from_user = models.ForeignKey(organisation_model, related_name='_unused_organisation_relation')

问题是当它创建relationship1 和relationship2 时它会崩溃,因为to_user 和from_user 与不同的模型有关系。如果您能帮助我解决问题或推荐另一种方式(不使用 django-friendship 包)以满足我的要求,我将非常高兴。

【问题讨论】:

  • 这种事情可以很容易地完成,无需第三方包。学习这些包比自己动手要花更多时间
  • mm,你有什么想法或推荐我的东西,教程或文档,因为我花了很多时间浏览 youtube 和其他资源,看看是否有人可以帮助我但不能'找不到任何东西:/

标签: python django foreign-key-relationship django-database


【解决方案1】:

https://github.com/Ry10p/django-Plugis/blob/master/courses/models.py

第 52 行

此外,Friend 模型的位置必须在 FriendRequest 模型之前,因为 FriendRequest 模型依赖于 Friend 的 ForeignKey。

例子:

class Author():
    name = models.CharField(max_length=100)
    bio = models.TextField(max_length=100)


class Article():
    author = models.ForeignKey(Author)
    text = models.TextField(max_length=500)
    publish_date = models.DateTimeField(null=True)

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 2012-01-27
    • 2011-12-01
    • 2012-10-28
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    相关资源
    最近更新 更多