简体   繁体   English

使用Django queryset在多对一字段中按值排序?

[英]Sort by a value in a many to one field with a django queryset?

I have a data model like this: 我有一个这样的数据模型:

class Post(models.Model)
    name = models.CharField(max_length=255)

class Tag(models.Model)
    name = models.CharField(max_length=255)
    rating = models.FloatField(max_length=255)
    parent = models.ForeignKey(Post, related_name="tags")

I want to get Posts that have a tag, and order them by the tags rating. 我想获取具有标签的帖子,并按标签等级对其进行排序。

something like: Posts.objects.filter(tags__name="exampletag").order_by("tags(name=exampletag)__rating") 类似于:Posts.objects.filter(tags__name =“ exampletag”)。order_by(“ tags(name = exampletag)__ rating”)

Currently, I am thinking it makes sense to do something like 目前,我认为做类似的事情很有意义

tags = Tags.objects.filter(name="sometagname").order_by("rating")[0:10]
posts = [t.parent for t in tags]

But I like to know if there is a better way, preferably querying Post, and getting me back a queryset. 但是我想知道是否有更好的方法,最好查询Post,然后再返回查询集。


Edit: 编辑:

I don't think this: ( Edit 2 - this does give the correct sorting! ) 我不这么认为:( 编辑2-这确实给出了正确的排序!

Posts.objects.filter(tags__name="exampletag").order_by("tags__rating")

will give the correct sorting, as it does not sort only by the related item with name "exampletag" 将给出正确的排序,因为它不会仅按名称为“ exampletag”的相关项目进行排序
Something like the following would be needed 需要以下内容

Posts.objects.filter(tags__name="exampletag").order_by("tags(name=exampletag)__rating")

I've been looking over the django docs, and it seem "annotate" nearly works - but I don't see a way to use it to select a tag by name. 我一直在查看django文档,似乎“注释” 几乎可以正常工作-但我看不到使用它来按名称选择标签的方法。


Edit 2 编辑2

Both the Answers are correct! 两个答案都是正确的! See my comments to observe some epic brain-farts (one test, the results WERE in order, the other i filter and sort by different tags!) 请参阅我的评论以观察一些史诗般的脑瘫(一项测试,结果按顺序排列,另一项则按不同标签过滤和排序!)

how it works 这个怎么运作

the query 查询

Posts.objects.filter(tags__name="exampletag").order_by("tags__rating")

and

Posts.objects.filter(tags__name="exampletag").filter(tags__name="someothertag").order_by("tags__rating")

will work correctly and by sorted by the rating of "exampletag" 可以正常工作,并按“ exampletag”的等级排序

it seems the tag(From a ForeignKey BackReference Set) used for sorting when calling order_by is the one in the first filter. 似乎用于当调用ORDER_BY是一个在第一过滤器排序的标签(从一个ForeignKey反向引用集)。

You can do like: 您可以像这样:

tags = Tags.objects.filter(name="sometagname")
posts =  Post.objects.filter(tags__in=tags).order_by('tags__rating')

甚至比Anush短,带有JOIN而不是子查询:

Post.objects.filter(tags__name='exampletag').order_by('tags__rating')

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

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