1

I have a model Van with a slug field and a price field. I am using MySQL. I have to save different prices for all 12 months. I am using JsonField.

class Van(models.Model):
    slug = models.SlugField(max_length=200)
    price = JSONField(null=True)

I am saving price like this and showing price of current month to visitor.

{'January': 987.0, 'February': 567.0, 'March': 567.0, 'April': 456.0, 'May': 6.0, 'June': 654.0, 'July': 456.0, 'August': 456.0, 'September': 456.0, 'October': 546.0, 'November': 89.0, 'December': 456.0}

Problem I have to add an filter for min and max price. I don't know how can I do this. I have tried this Van.objects.exclude(price__June__gte=340) but this is raising error

Unsupported lookup 'June' for JSONField or join on the field not permitted.

I searched the error and found this only work in postgres.

I know this solution query = User.objects.filter(data__campaigns__contains=[{'key': 'value'}]) but i don't need exact matching.Is there any other method to filter vans by price?

Ralf
  • 16,086
  • 4
  • 44
  • 68
sandeep
  • 721
  • 1
  • 7
  • 14
  • do you check this? query = User.objects.filter(data__campaigns__contains=[{'key__gte': 'value'}]) – Saeed Ramezani Jan 18 '21 at 11:30
  • Do you have to use a `JsonField`? The query would be much simpler and faster by adding 12 price fields to the model, one for each month. – Ralf Jan 18 '21 at 11:35
  • @Saeed, I am using django-jsonfield which is a textfield. Django converts it into json by loads function. Thats why lookups will not work. Check this answer to understand clearly https://stackoverflow.com/a/53986802/10084728. Thanks for suggestion. – sandeep Jan 18 '21 at 11:36
  • @Ralf, Actually I don't know actual categories for price. 2 weeks ago, clients wanted price for 3 seasons, now for all 12 months. It may change again. That's why I am using JSON field. – sandeep Jan 18 '21 at 11:38

0 Answers0