【问题标题】:Extract OneToOne Field in django model在 django 模型中提取 OneToOne 字段
【发布时间】:2016-06-10 20:46:17
【问题描述】:
class Post(models.Model):
    created_time = models.DateTimeField()
    comment_count = models.IntegerField(default=0)
    like_count = models.IntegerField(default=0)
    group = models.ForeignKey(Group)

class MonthPost(models.Model):
    created_time = models.DateTimeField()
    comment_count = models.IntegerField(default=0)
    like_count = models.IntegerField(default=0)
    group = models.ForeignKey(Group)
    post = models.OneToOneField(Post)

我使用这两个模型。 MonthPost 是 Post 的一部分。 当过滤日期小于月份时,我想使用 MonthPost。

_models = Model.extra(
            select={'score': 'like_count + comment_count'},
            order_by=('-score',)
        ) 

我额外使用了以上两个模型。 Post 效果很好,但 MonthPost 不行。

django.db.utils.ProgrammingError: column reference "like_count" is ambiguous
LINE 1: ... ("archive_post"."is_show" = false)) ORDER BY (like_count...

这是错误信息。

_models.values_list("post", flat=True)

然后,我想从 MonthPost 中提取 OneToOne 字段(帖子)。 我尝试使用 values_list("post", flat=True)。它只返回 id 列表。 我需要发布 django rest 框架的对象列表。

【问题讨论】:

    标签: python django django-queryset django-orm


    【解决方案1】:

    我不太明白您想用 MonthPost 模型实现什么目标,以及为什么它会重复 Post 字段。话虽如此,我认为您可以使用此信息获得所需的结果。

    首先extra 已被贬值,请参阅docs on extra。无论哪种情况,您的选择都不是有效的 SQL 语法,您的查询应该看起来更像这样:

    annotate(val=RawSQL(
                "select col from sometable where othercol =%s",
                (someparam,)))
    

    但是,您在这里所追求的既不需要额外的也不需要 RawSql。只有在没有内置方法来实现预期结果时才应使用这些方法。当使用 RawSql 或额外时,您必须为您的特定支持定制 SQL。 Django 为此类查询内置了方法:

    qs = Post.objects.all().annotate(
        score=(Count('like_count') + Count('comment_count'))
    

    values_list() 查询需要明确列出相关模型中的所有字段以及额外或带注释的字段。对于 MonthPost,它应该如下所示:

    MonthPost.objects.all().values_list('post', 'post__score', 'post__created_time')
    

    最后,如果 MonthPost 的目的只是列出给定月份得分最高的帖子,您可以完全消除 MonthPost 模型并为此查询您的 Post 模型。

    import datetime
    today = datetime.date.today()
    
    # Filter for posts this month
    # Annotate the score
    # Order the results by the score field
    qs = Post.objects\
             .filter(created_time__year=today.year, created_time__month=today.month)\
             .annotate(score=(Count('like_count') + Count('comment_count'))\
             .order_by('score')
    
    # Slice the top ten posts for the month
    qs = qs[:10]
    

    上面的代码未经测试,但应该能让您更好地了解如何执行这些类型的查询。

    【讨论】:

      猜你喜欢
      • 2015-03-16
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      相关资源
      最近更新 更多