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?
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.
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.
blocked_delivery_times = BlockedDeliveryTime.objects.filter(delivery_date=delivery_date) \ .values('delivery_time') delivery_times = DeliveryTime.objects.exclude(id__in=blocked_delivery_times)
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.
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