Computer scienceBackendDjangoAdvanced QuerySet usage

Q object

Difficult choice

Report a typo

The Phone model is a list of cell phones with different characteristics such as brand, model, operating system, memory capacity, and price. You need to create a sophisticated filter to find cell phones that meet the following criteria:

  • Android (OS='Android') or iOS (OS='iOS') operating system;
  • The cost of the cell phone must be less than 1000 (price < 1000);
  • Storage capacity of 64 GB or more (storage >= 64);
  • The brand of the cell phone must be one of the following: Samsung, Apple, Google, or OnePlus:
class Phone(models.Model):
    brand = models.CharField(max_length=50)
    model = models.CharField(max_length=100)
    OS = models.CharField(max_length=20)
    storage = models.IntegerField()
    price = models.DecimalField(max_digits=8, decimal_places=2)
Write a program in Python 3
os_filter = Q(OS=...) | Q(OS='iOS')
price_filter = Q(...=1000)
storage_filter = Q(...)
brand_filter = Q(...=['Samsung', 'Apple', 'Google', 'OnePlus'])

result_filter = os_filter & price_filter & storage_filter & brand_filter
suitable_phones = Phone.objects.filter(result_filter)
___

Create a free account to access the full topic