【问题标题】:is it possible to Only pull related users through foreign key relationship, once in django一次在django中是否可以只通过外键关系拉取相关用户
【发布时间】:2011-05-04 13:49:18
【问题描述】:

嗨,我对 django 的奇妙世界还很陌生!

基本上我正在从事一个项目,该项目需要我创建一个相当独特的电子邮件通知系统,当网站上发布新的博客文章时,用户可以使用该系统来优化他们通过电子邮件收到的更新。

我想我会有很多关于这个项目的问题,因为它被证明是一个非常陡峭的学习曲线,所以我想我先自己尝试一下,然后当我遇到困难时跑到这里寻求帮助!

基本上,用户可以选择接收以下更新 所有新的博客文章 或从他们最喜欢的作者的复选框中选择 等等

我遇到的第一件事是将用户从数据库中拉出。我知道如何获取每个博客的所有用户详细信息,但这显然让我返回了已发布多个博客的用户的重复用户详细信息。所以我需要一种方法来只获取那些发布博客的用户的用户信息,并且只获取他们的详细信息一次。

型号

class Blog(models.Model):

     user = models.ForeignKey(User, help_text = "The User posting this blog entry")
     news = models.ForeignKey(News, unique = True, blank = True, null = True, help_text = "Is this Blog entry related to a news posts IE and Expert Analysis")
     title = models.CharField(max_length = 120, help_text = "The Title of this blog entry")
     slug = models.SlugField(max_length = 150, help_text = "This Field is auto-populated by the title field, its simply used for the CMS urls")
     info = models.TextField()
     categories = models.ManyToManyField(Categories)
     sectors = models.ManyToManyField(Sectors)
     tags = models.ManyToManyField(Tags)
     published = models.DateTimeField()
     status = models.CharField(max_length=1, choices=STATUS_CHOICES, default = 'd')

     class Meta:
         verbose_name_plural = "Blog entries"
         verbose_name = "Blog"
         ordering = ['-published']

     def __unicode__ (self):
         return self.title

如您所见,我使用 django 的用户模型作为外键来存储作者的详细信息。我应该放弃这种方法并为博客作者建立一个单独的模型,还是可以使用内置的用户模型来实现我想要做的事情。

所以总结一下我的目标是能够获得所有发布过博客文章的用户的列表,但只获取他们的详细信息一次,从而给我一个名称和 ID 列表,以便我可以创建一个表单使用用户可以勾选以选择接收更新的复选框!

提前感谢您的帮助!!

【问题讨论】:

    标签: python django django-models django-users


    【解决方案1】:

    您可以对至少有一个博客条目的用户进行一次查询:

    User.objects.exclude(blog=None)
    

    【讨论】:

    • 非常感谢您的快速回复,这很有效!有点不好意思,没看懂!再次感谢!
    【解决方案2】:

    我不确定 Daniel 的解决方案是如何工作的,因为 User 模型中没有与您的 Blog 模型相关的 blog 字段(我知道)。但如果它有效,那就太好了。

    如果您发现您仍然遇到问题,那么也许这会有所帮助。我有两个选择。 首先,如果您只需要 id 和名称,那么这可能会起作用。

    users = Blog.objects.all().order_by('user__username').values('user__id', 
            'user__username').distinct()
    

    其次,如果您想要实际的 User 对象,那么这可能就是您所追求的。

    userids = Blog.objects.all().values_list('user__id', flat=True)
    users = User.objects.filter(pk__in=userids).order_by('username')
    

    【讨论】:

    • 嘿,感谢您的回答,这与我正在尝试的方式一致,所以很高兴知道我哪里出错了。
    猜你喜欢
    • 2016-11-28
    • 2021-01-04
    • 2015-12-20
    • 1970-01-01
    • 2013-07-20
    • 2015-04-03
    • 2021-11-17
    • 2017-09-16
    • 1970-01-01
    相关资源
    最近更新 更多