[Python] How to check if a django queryset has a matching manytomany + foreignkey?

Discussão em 'Python' iniciado por Stack, Abril 27, 2025.

  1. Stack

    Stack Membro Participativo

    I try to check - in Djnago - if a user made queryset has two fields out of three which match 100%.

    class Foo(models.Model):
    # ...
    free_field = models.ForeignKey(FreeModel, ...)
    must_match_m2m_field = models.ManyToManyField(ManyModel, ...)
    must_match_fk_field = models.ForeignKey(BarModel, ...)
    # ...



    So, user generates a queryset of the "Foo" model (with several objects in it), which may contain many objects with a) different FreeModels, and b) precisely matching ManyModels & BarModels. In backend I need to check that all ManyModels and BarModels match in the query.

    for the ForeignKey objects I made following (I think its fair enough):

    def check_same_objects(object_list):
    return len(set(object_list)) == 1

    check_bars = check_same_objects(qs_foo.values_list('must_match_fk_field', flat=True))


    I made this for comparing the lists of objects in the manytomany fields of each object:

    def check_same_lists(object_lists):
    for lst in object_lists:
    if set(lst) != set(object_lists[0]):
    return False
    return True


    should_match_foos = []
    for e in qs_foo:
    should_match_foos.append(e.must_match_m2m_field.all().values_list('id', flat=True))
    check_manies = check_same_lists(should_match_foos)

    # finally checking both 'must-match-fields':
    check_both = all([check_bars, check_manies])



    What is the more elegant pythonic/djnago variant of checking if theese two fields match 100% in the whole qs?

    Continue reading...

Compartilhe esta Página