大家好我试图弄清楚如何根据manyToMany字段订购查询集,但我也需要过滤该字段。这是确切的问题。
qs = Drink.objects.all()
我想通过相关字段ingredientsuserneeds
型号:
class IngredientsUserNeeds(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
drinks = models.ManyToManyField(Drink)
count_need = models.IntegerField(default=0)
class Drink(models.Model):
name = models.CharField(max_length = 1000, null=True, blank=True)
user = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
在DRF列表视图中,我想通过饮料的ingredientuserneeds_set
对查询集进行排序,但是会被用户过滤,该用户将返回长度为1的查询集,最后按该单个对象进行排序&# 39; s count_need在查询集中。这有点像
qs = qs.order_by('ingredientsuserneeds_set__filter(user=user)__first()__count_need')
但显然,你不能做我输入的内容。有什么想法吗?
答案 0 :(得分:0)
这应该可以解决问题:
from django.db import models
from django.db.models import Case, When, F
Drink.objects.all().annotate(
count_need=Case(When(
ingredients__user__email='wanaryytel@outlook.com', then=F('ingredients__count_need')),
output_field=models.IntegerField()
)
).first().count_need