如何在查询中比较模型的两个字段? [英] How can I compare two fields of a model in a query?

查看:87
本文介绍了如何在查询中比较模型的两个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个管理命令,该命令将根据建议的价格过滤产品的原始价格。

I'm writing a management command which will filter a product's original price with suggested prices.

我的产品模型如下:

class Suggestion(models.Model):
    ....
    price = models.IntegerField()

class Product(models.Model):
    price = models.IntegerField()
    suggestions = models.ManyToManyField(Suggestion)

我要过滤所有其产品价格等于最低建议。应该是这样的:

I want to filter all products whose price is equal to minumum suggestion. Something should like :

Product.objects.filter(price = minumum(suggestions))

AND

我要过滤产品中建议包含产品原始价格的产品。应该是这样的:

I want to filter products where the suggestions contains the Product's original price. Something should like :

Product.objects.filter(price__in = self.suggestions)

问题是我无法使用for循环查看每个产品的最低建议,并且您猜不到我无法使用对象的自我,那么如何在查询中比较模型的两个字段?

The problem is I can't use a for-loop to look each Product's minumum suggestion and as you guess I can't use object's self either, so how can I compare two fields of a model in a query ?

推荐答案

from django.db.models import F
Product.objects.filter(price__in=F('suggestions'))

这篇关于如何在查询中比较模型的两个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆