B
B
blohinn2018-09-03 18:57:46
Django
blohinn, 2018-09-03 18:57:46

How to properly filter records (Django ORM) with ManyToMany relation?

There are two entities:
The first one orders a service, the second one provides a service (Customer - Contractor).
We also have so-called "features". For example: home visits, free consultation, free first call, priority tech. support.
The customer, when creating a request for execution, can indicate which "features" he is interested in. For example, only priority tech. support and home visits.
The contractor, in his profile, indicates which additional He has "features". For example, he is only interested in going home and that's it.
It is necessary to formulate one query (Django ORM) that would work like this:
1) The customer is only interested in home visits, and the contractor has a bunch of other "features", but home visits are also available.
2) The customer is interested in home visits and priority tech. support, however, the service is in the interests of only calling home and everything, the priority of those. does not provide support. This means that he does not see this request for execution, but those who support, among other "features" and those that the user requested, see it.
3) The customer is not interested in any additional. features - everyone can see this application.
What we have:

class Feature(models.Model):
    AVAILABLE_FEATURES = (
        ('free_diagnostics', 'Бесплатная консультация'),
        ('call_home', 'Возможна консультация на дому')
    )
    feature = models.CharField(max_length=32, choices=AVAILABLE_FEATURES, unique=True)
 
class Executor(models.Model):  # Исполнитель
    # ...
    features = models.ManyToManyField(Feature, blank=True, related_name='executors')
 
class ClientOrder(models.Model):  # Заказчик
    # ...
    features = models.ManyToManyField(ServiceFeature, blank=True, related_name='client_orders', verbose_name='Доп. услуги')
 
def orders_list(request):
    # ...
    # Наша попытка. Дублирует записи, и не отвечает критериям, которые я описал выше.
    orders_l = orders_l.filter(features__in=executor_obj.features.all())
    # ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
olexndr090, 2022-02-18
@olexndr090

I have the same problem, when using in in filter, there are duplicate entries.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question