2

I have models called Stores and SaleItems which look some what like this.

class Stores(models.Model):
    name = models.CharField(unique=True, max_length=20)


class SaleItems(models.Model):
    sale_by = models.ForeignKey(Stores)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

So I need to retrieve sale items based on the following conditions.

  1. If its not my store, then leave out items having start_date greater than today and end_date lesser than today.
  2. If its my store, then get items irrespective of start_date and end_date.

So in my views.py, this is how far I have come up.

class SaleItemsView(viewsets.ModelViewSet):
    querys = SaleItems.objects.all()


def get_queryset(self):
    #get my store id
    store_id = self.request.query_params.get('store_id')
    querys = SaleItems.objects\
            .exclude(store__ne=store_id, end_date__lt=timezone.now())\
            .exclude(store__ne=store_id, start_date__gt=timezone.now())
    return querys

But it seems django doesn't have not equal operator any more. Is there any other way I can achieve this?

Karthik RP
  • 1,028
  • 16
  • 26

1 Answers1

1

I think you would combine the records for each of your conditions using Qobjects, then do distinct() to remove duplicates:

now = timezone.now()
items_within_date_range = Q(start_date__lte=today, end_date__gte=today)
curr_store_items = Q(store=store_id)

result = SaleItems.objects.filter(items_within_date_range|curr_store_items).distinct()

The first query would get all items within time range for both your store and other stores, second query would get all items for your store, then combine then would get everything.

Shang Wang
  • 24,909
  • 20
  • 73
  • 94