【问题标题】:Trying and expand the contrib.auth.user model and add a "relationships" manage尝试扩展 contrib.auth.user 模型并添加“关系”管理
【发布时间】:2011-01-06 22:48:29
【问题描述】:

我有以下模型设置。

from django.db import models
from django.contrib.auth.models import User

class SomeManager(models.Manager):
    def friends(self):
        # return friends bla bla bla


class Relationship(models.Model):
    """(Relationship description)"""
    from_user = models.ForeignKey(User, related_name='from_user')
    to_user = models.ForeignKey(User, related_name='to_user')
    has_requested_friendship = models.BooleanField(default=True)
    is_friend = models.BooleanField(default=False)

    objects = SomeManager()

relationships = models.ManyToManyField(User, through=Relationship, symmetrical=False)
relationships.contribute_to_class(User, 'relationships')

这里我使用用户对象并使用contribute_to_class 将“关系”添加到用户对象。关系出现了,但如果调用 User.relationships.friends 它应该运行 friends() 方法,但它失败了。有什么想法我会怎么做?

谢谢

【问题讨论】:

  • 你为什么不使用用户配置文件功能? docs.djangoproject.com/en/dev/topics/auth/… 这应该是向User 类添加功能的正确方法。
  • 我希望将它作为一个“应用程序”发布,并不是每个用户都有配置文件模块设置。
  • 改成settings的一行代码,大家都可以配置好配置文件模块了。

标签: python django model authentication


【解决方案1】:

我会这样做。

f= Relationships.objects.filter( from_user=some_user, is_friend=True )

这样就省去了与用户纠缠不清的麻烦。

【讨论】:

    【解决方案2】:

    也许您在调用中缺少“.objects”:

    User.relationships.objects.friends()
    

    【讨论】:

    • 抛出错误 'ManyRelatedManager' 对象没有属性 'objects'
    【解决方案3】:

    您需要告诉 Django 使用您的管理器进行相关查找 - 默认情况下,它使用标准的查找。您需要在 Manager 上设置 use_for_related_fields - 请参阅 the documentation on this

    【讨论】:

      猜你喜欢
      • 2019-07-29
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      相关资源
      最近更新 更多