How do I filter django models based on product fields?

I am trying to run a filter command, using related fields; and am unsure how to go about it:

class Listing(models.Model):
    name = models.CharField(max_length=150)
    slug = models.SlugField()
    description = models.TextField()
    catchphrase = models.TextField(null=True, blank=True)
    picture_0 = models.ImageField(upload_to = "mainimages")
    picture_1 = models.ImageField(null=True, blank=True, upload_to = "./product/static/product/imgs")
    picture_2 = models.ImageField(null=True, blank=True, upload_to = "./product/static/product/imgs")
    short_term_price = models.IntegerField(default=0)
    long_term_price = models.IntegerField(default=0)
    tax = models.IntegerField(default=0)
    tag = models.ForeignKey('Tag', on_delete=models.PROTECT)

    def __str__(self):
        return self.name

class Order(models.Model):
    listing = models.ForeignKey(Listing, on_delete=models.PROTECT)
    customer = models.ForeignKey(Customer, on_delete=models.PROTECT)
    lease_date = models.DateField()
    clear_date = models.DateField()
    price = models.IntegerField(default=0) #cents

    def __str__(self):
        return self.listing.name
    
    def get_display_price(self):
        return "{0:.2f}".format(self.price / 100)

The general idea is that the user provides a start date and an end date and Django only returns the listings that aren't already in an order in that timeframe. I am unsure how to go about the view function:

def search_products(request, start_date, end_date):
    listing = Listing.objects.select_related('order').all()

I will provide an answer as if you are using the lease_date to do the filtering. There is a couple of ways to achieve this. One is:

listing_qs = Listing.objects.filter(
pk__in=Order.objects.exclude(lease_date__range(start_date,end_date)).select_related('listing').values_list('listing__pk')
)

Code breakdown:

  • retrieve the orders by excluding those whose lease date is in between the provided timeframe
  • selecting the listing's pk (via values('listing__pk')) you can select any other attribute you want
  • using the result of the 2 previous instructions to get the Listing objects since we have the list of pk.

Another way: Just exclude all the Listing objects whose lease date is in between the provided timeframe

Listing.objects.exclude(order_set__lease_date__range=(start_date,end_date))

I hope this helps.

Back to Top