There is a model:

class Artikul_cabinets(models.Model): artikul_cabinets = models.CharField(verbose_name="Артикул шкафа", max_length=20) title_cabinets = models.CharField(verbose_name="Описание шкафа", max_length=200) width_cabinets = models.ManyToManyField(Width_cabinets) depth_cabinets = models.ManyToManyField(Depth_cabinets) unit_cabinets = models.ManyToManyField(Unit_cabinets) weight_cabinets = models.ManyToManyField(Weight_cabinets) type_cabinets = models.ForeignKey(Type_cabinets, default=1) color_cabinets = models.ForeignKey(Color_cabinets) glass_cabinets = models.ManyToManyField(Glass_cabinets) class Meta: verbose_name_plural = "Артикул шкафа" def __str__(self): return self.artikul_cabinets 

It is necessary to make a selection on the field:

 glass_cabinets = models.ManyToManyField(Glass_cabinets) 

I do the selection as follows:

 data = Artikul_cabinets.objects.filter(Q(glass_cabinets=artgen['perf']) & Q(glass_cabinets=artgen['glass']) 

And an empty QuerySet returned to me, although in the database the element with the perf and glass parameters is present in the same record.

Tell me what I'm doing wrong. I tried:

 data = Artikul_cabinets.objects.filter(Q(glass_cabinets=artgen['perf']), Q(glass_cabinets=artgen['glass']) 

and also does not work, although if you set the operator | This condition OR works fine.

  • It's not entirely clear what you are trying to do. How can one field be simultaneously equal to artgen['perf'] and artgen['glass'] (provided that artgen['perf'] and artgen['glass'] different)? - awesoon
  • artgen['perf'] and artgen['glass'] different. The glass_cabinets field has a glass_cabinets connection to the ManyToManyField model. and accordingly in one record there can be several glass_cabinets values. Or something I do not understand. Example - clip2net.com/s/3uqrPGX - Andrey Bessonov
  • Maybe it will be easier to pull out all Artikul_cabinets through feedback in the Glass_cabinets objects? - awesoon

1 answer 1

The problem was solved like this:

 Artikul_cabinets.objects.filter(glass_cabinets=artgen['perf']).filter(glass_cabinets=artgen['glass'])