Home > Software design >  How to filter on two different fields in on a Django query?
How to filter on two different fields in on a Django query?

Time:12-29

I have the following model in my Django project:

class History(models.Model):
    item = models.ForeignKey(Item,on_delete=models.CASCADE)
    timestamp = models.BigIntegerField(default=0)
    price = models.FloatField()

And I want to filter on based on the item and the timestamp. The idea is I want to check if a model instance exist or not before I create a new instance.

Current I have the following:

History.objects.filter(timestamp=timestamp).exists() == False:

I filter based on the timestamp but I want to do something like filtering by both the item and the timestamp at the same time.

For example if I have item="phone", timestamp = 1640736000

item = Item
timestamp = 1640736000
History.objects.filter(timestamp=timestamp and item=item).exists() == False:

But the above doesn't seem to work.

How do i go about this?

Edited:

Below is the Item model,

class Item(models.Model):
    name = models.CharField(default="", max_length=50)
    description = models.TextField(default="No Description")
    homepage = models.TextField(default="No Homepage")

    
    def __str__(self):
        return "{}-{}".format(self.Item,self.name)

CodePudding user response:

To filter on multiple fields in the same filter you provide the lookups as separate keyword arguments. To filter on a relationship, like a ForeignKey, use double underscores to follow the relationship

item = "phone"
timestamp = 1640736000
History.objects.filter(timestamp=timestamp, item__name=item).exists()
  • Related