Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django excluding one queryset from another

I have the following two models:

class DeliveryTime(models.Model):    delivery_time = models.CharField(max_length=15)  class BlockedDeliveryTime(models.Model):    delivery_date = models.DateField()    delivery_time = models.ForeignKey(DeliveryTime)  

I want to return all the available delivery times for a day i.e. all DeliveryTime excluding the BlockedDeliveryTime.

 blocked_delivery_times = BlockedDeliveryTime.objects.filter(delivery_date=delivery_date)  delivery_times = DeliveryTime.objects.all() 

From delivery_times queryset I want to remove all blocked_delivery_times.delivery_time

How can I do that? Any suggestions?

like image 918
reevh Avatar asked Mar 08 '14 08:03

reevh


People also ask

How do I merge two Querysets in Django?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function.

What is filter Django?

Django-filter is a generic, reusable application to alleviate writing some of the more mundane bits of view code. Specifically, it allows users to filter down a queryset based on a model's fields, displaying the form to let them do this. Adding a FilterSet with filterset_class. Using the filterset_fields shortcut.


2 Answers

blocked_delivery_times = BlockedDeliveryTime.objects.filter(delivery_date=delivery_date) \     .values('delivery‌​_time') delivery_times = DeliveryTime.objects.exclude(id__in=blocked_delivery_times) 
like image 147
Paul Draper Avatar answered Oct 14 '22 15:10

Paul Draper


With the release of Django 1.11 you can use difference, which takes advantage of the EXCEPT SQL operator. I think it might be more efficient because you aren't evaluating a query to get a list of values.

like image 45
Harel Avatar answered Oct 14 '22 14:10

Harel