Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two fields of a model in a query?

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

I have a product model which looks like :

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)

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 ?

like image 472
iva123 Avatar asked Aug 14 '11 00:08

iva123


People also ask

How do I compare two columns of data in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.

How do I match two column values in SQL?

Here's the generic SQL query to two compare columns (column1, column2) in a table (table1). mysql> select * from table1 where column1 not in (select column2 from table1); In the above query, update table1, column1 and column2 as per your requirement.

How do you compare two columns values in two different tables in SQL?

Using joins to compare columns by priority among the table. For example, left join returns all values from the first table and null value for the not-matched records from the second table. Similarly, we can use right join, inner join, full join and self join as per our requirements.

How do you compare two columns in access?

To compare two tables by using a field as a criterion, you create a select query that includes both tables. You include the fields that you want to display, and you also include the field that corresponds to the field that you want to use as a criterion. You then create a criterion to compare the tables.


1 Answers

from django.db.models import F
Product.objects.filter(price__in=F('suggestions'))
like image 186
mossplix Avatar answered Nov 13 '22 12:11

mossplix