簡體   English   中英

在Django模型中提取OneToOne字段

[英]Extract OneToOne Field in django model

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框架的對象列表。

我不太了解您要使用MonthPost模型實現的目標以及為什么它會復制Post字段。 話雖如此,我想您可以通過此信息獲得所需的結果。

首先, extra已貶值,請參閱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]

上面的代碼未經測試,但是應該為您提供更好的處理這些類型查詢的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM