【问题标题】:Querying PostgreSQL database (with Django) for only objects with relations仅查询具有关系的对象的 PostgreSQL 数据库(使用 Django)
【发布时间】:2017-01-12 14:14:53
【问题描述】:

我目前正在通过官方教程学习 Django,并决定按照here 的建议尝试添加一些额外的功能和测试。

我现在在数据库中有两个模型,它们看起来基本上是这样的:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

我设置了一个视图来显示问题列表。我想要做的是为视图创建一个查询,该查询将只包括具有相关选择的问题对象。任何没有相关选择对象的问题对象都不应包含在结果集中。此查询还忽略了未来的问题并对它们进行排序,但这部分很好,并且在教程之外。

这是我到目前为止想出的。它似乎有效,但我不禁认为我以一种非常落后和低效的方式完成了它。是否可以创建一个查询来处理数据库中的所有内容,而不是两个查询和一个列表理解??

choices = Choice.objects.prefetch_related(
    'question').distinct('question')
question_ids = [x.question.id for x in choices]
return Question.objects.filter(
    id__in=question_ids).filter(
    pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

【问题讨论】:

    标签: python django postgresql


    【解决方案1】:

    您可以通过与之关联的Choice 对象的计数来注释Question 查询集,然后排除计数为零的对象:

    from django.db.models import Count
    questions = Question.objects \
            .annotate(choice_cnt=Count('choice')) \
            .exclude(choice_cnt=0) \
            .filter(pub_date__lte=timezone.now()) \
            .order_by('-pub_date')[:5]
    

    【讨论】:

    • 效果很好!感谢您的快速回答和改进的格式。
    • 我很乐意提供帮助。
    猜你喜欢
    • 2019-08-31
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2020-12-21
    • 2021-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多