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 ?
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.
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.
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.
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.
from django.db.models import F
Product.objects.filter(price__in=F('suggestions'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With