L
L
Leonid2020-02-06 22:58:59
Django
Leonid, 2020-02-06 22:58:59

How to create an array filter in django orm?

Given 2 models:

class Country(models.Model):
   title = models.CharField(
        max_length=120, verbose_name="Наименование"
    )

class Product(models.Model):
  country = models.ForeignKey(
        Country,
        on_delete=models.CASCADE,
        blank=True
    )


the array id Country comes to the view from the form - ['1' , '2' , '5']
how to form a query to select the Product country field of which is included in this array?
for example:
Magadascar object of type Country has id 1
Egypt object of type Country has id 2

you need to select all Product, where id country is in the array ['1' , '2' ]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2020-02-06
@stilet69

Product.objects.filter(country__id__in=[1,2])

D
Dmitry Sviridov, 2020-02-06
@dimuska139

products = Product.objects.filter(country_id__in=countries_ids)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question