简体   繁体   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)

I use this two models. 我使用这两种模型。 MonthPost is part of Post. MonthPost是Post的一部分。 I want to use MonthPost when filtered date is smaller than month. 我想在过滤日期小于月份时使用MonthPost。

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

I use extra about above two models. 我在上述两个模型上使用了更多内容。 Post works well, but MonthPost doesn't work. Post效果很好,但是MonthPost不起作用。

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

This is the error message. 这是错误消息。

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

And then, I want to extract OneToOne field(post) from MonthPost. 然后,我想从MonthPost中提取OneToOne字段(帖子)。 I try to use values_list("post", flat=True). 我尝试使用values_list(“ post”,flat = True)。 It return only id list. 它仅返回ID列表。 I need to post object list for django rest framework. 我需要发布Django Rest框架的对象列表。

I don't' quite understand what you are trying to achieve with your MonthPost model and why it duplicates Post fields. 我不太了解您要使用MonthPost模型实现的目标以及为什么它会复制Post字段。 With that being said I think you can get the results you want with this info. 话虽如此,我想您可以通过此信息获得所需的结果。

First of all extra is depreciated see the docs on extra . 首先, extra已贬值,请参阅extra上的文档 In either case, your select is not valid SQL syntax, your query should look more like this: 无论哪种情况,您的选择都不是有效的SQL语法,您的查询应该看起来像这样:

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

However, what you are after here requires neither extra or RawSql. 但是,您所追求的不需要额外的或RawSql。 These methods should only be used when there is no built in way to achieve the desired results. 仅当没有内置方法来实现所需结果时,才应使用这些方法。 When using RawSql or extra, you must tailor the SQL for your specific backed. 使用RawSql或其他版本时,必须为特定的支持量身定制SQL。 Django has built in methods for such queries: Django内置了用于此类查询的方法:

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

A values_list() query needs to explicitly list all fields from related models and extra or annotated fields. values_list()查询需要显式列出相关模型中的所有字段以及额外的或带注释的字段。 For MonthPost it should look like this: 对于MonthPost,它应如下所示:

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

Finally, if the purpose of MonthPost is simply to list the posts with he greatest score for a given month, you can eliminate the MonthPost model entirely and query your Post model for this. 最后,如果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]

The code above is not tested, but should give you a better handle on how to perform these types of queries. 上面的代码未经测试,但是应该为您提供更好的处理这些类型查询的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM