Home > Enterprise >  Django conditional many-to-many relation exists check
Django conditional many-to-many relation exists check

Time:07-30

The model is:

class RecordModel(BaseModel):
    visibility_setting = models.PositiveIntegerField()
    visible_to = models.ManyToManyField(UserModel, blank=True)

I need to return rows depending on row visibility_setting:

  • if visibility_setting == 0 - return row without any checks,
  • if visibility_setting == 1 - I need to check if user is in visible_to m2m relation exists.

In second case query works okay, but in first case my approach of setting None on first case not working (as expected):

Feed.objects.filter(
    visible_to=Case(
        When(visibility_setting=0, then=None),  # no data returned in this case, but I want to 
                                                # return all rows with visibility_setting=0
        When(visibility_setting=1, then=user.id),  # rows with visibility_setting=1 are queried okay
    )
)

I am a little bit stuck which way to use in this situation? Can we not apply case at all in some conditions or use some specific default to skip visible_to relations check?

CodePudding user response:

You can .filter(…) [Django-doc] with:

from django.db.models import Q

Feed.objects.filter(Q(visibility_setting=0) | Q(visible_to=my_user)).distinct()

the .distinct() call [Django-doc] prevents returning the same Feed multiple times.

  • Related