Search code examples
pythondjangodjango-modelsdjango-ormpep8

Django breaking long lookup names on queries


Let's assume there is a line of code to perform a query using the Django ORM that contains a very long 'lookup name':

QuerySet.filter(myfk__child__onetoone__another__manytomany__relation__monster__relationship__mycustomlookup=':P')

I'd like to break the line to follow pep8, specially 79 characters limit

I know we can do something like:

   QuerySet.filter(
      **{
        'myfk__child__onetoone__another' 
        '__manytomany__relation__monster' 
        '__relationship__mycustomlookup': ':P'
      }
    )

But I'm wondering if there is another, maybe more pythonic/accepted, way ?


Solution

  • Maybe using LOOKUP_SEP to join the lookup names is a bit more paletable?

    from django.db.models.constants import LOOKUP_SEP
    
    lookup = LOOKUP_SEP.join(['myfk', 'child', 'onetoone', 'another', 'manytomany',
                              'relation', 'monster', 'relationship',
                              'mycustomlookup'])
    
    QuerySet.filter(**{lookup:':P'})