2016-02-27 84 views
1
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。django模型中提取OneToOne字段

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

我使用额外约两个以上的模型。邮政运作良好,但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字段(post)。 我尝试使用values_list(“post”,flat = True)。它只返回id列表。 我需要发布django rest框架的对象列表。

回答

0

我不太理解你想用你的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模型和查询后您的模型这个。

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] 

上面的代码没有测试,但应该给你关于如何执行这些类型的查询更好地处理。