Home > front end >  How to filter Django Model instances based on a function defined inside the model?
How to filter Django Model instances based on a function defined inside the model?

Time:06-16

I have a model for an item, it has a function that tells if the item is still on auction depending on an end date.

class Catalogue(models.Model):
    name = models.CharField(max_length=256)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    end_date = models.DateTimeField()

    def auction_status(self):
        now = timezone.now()
        return now < self.end_date

In a class view i want to filter only those instances where the auction_status is true. Something along the lines of :

class AuctionOverView(ListView):
    model = Catalogue
    template_name = 'administration/catalogue.html'

    def get_queryset(self):
        try:
            return Catalogue.objects.filter(auction_status=False)
        except:
            raise Http404()

But i obviously can not filter based on a function definition. How to workaround this?

CodePudding user response:

With QuerySet you can not filter on property or function of model.

But in your case, you can do like below:

return Catalogue.objects.filter(end_date__lt=timezone.now())

CodePudding user response:

You could add @property decorator to your auction_status function, but this won't work with Django filters. There are some workarounds discussed here and here.

  • Related