0

Program versions:
Django 3.1.13
Python 3.8.10

My models.py:

# Create your models here.

class Odorant(models.Model):
    Pubchem_ID = models.IntegerField(primary_key = True)
    Name = models.CharField(max_length =50)
    Ruletype = models.TextChoices ('Ruletype', 'Satisfied Unsatisfied')
    Rule_of_Five = models.CharField(max_length = 20, choices = Ruletype.choices)
    Rule_of_Three = models.CharField(max_length = 20, choices = Ruletype.choices)
    Ghose_Filter = models.CharField(max_length = 20, choices = Ruletype.choices)

I would love to retrieve all the odourants that satisfies one of the rules and also the ones that satisfy all the rules at the same time and show them in html page. I have already configured urls.py and views.py but I miss the correct function to query the database.
If more code is needed, feel free to ask.
Any suggestion? Thank you all.

Giuliano
  • 27
  • 6

1 Answers1

1

This is something that's answered in Django's queryset documentation. One way to accomplish this is by chaining exclude functions.

It doesn't make sense to also save conditions that satisfy all of your rules in the same queryset, so save that separately. If you have any questions about filtering out empty values, there's a very good answer found in this post.

satisfy_one_or_more_rules = Odorant.objects\
    .exclude(Rule_of_Five='')\
    .exclude(Rule_of_Three='')\
    .distinct()

satisfy_all_rules = Odorant.objects\
    .exclude(Rule_of_Five='', Rule_of_Three='')
Lzak
  • 373
  • 1
  • 8