3

Field lookups in django use field names in the form in which they are declared in the code. Is there any way to provide a custom name for a field, to be used in lookups only?

I would like to use it to make a field read-only, but still be able to use it normally in queries.

For example, if the model looks like this:

class Flight(models.Model):
    _cancelled = models.BooleanField()

    @property
    def cancelled(self):
        return self._cancelled

Then filtering has to be done like this:

Flight.objects.all().filter(_cancelled=True)

And since we want the outside world to use cancelled as the property, it would be nicer if we could write:

Flight.objects.all().filter(cancelled=True)

I have tried using Field.db_column property, but it only appears to change the column name in the database.

For the sample case above, a proper Manager would be enough to handle this, but things become more complicated if there is another model with ForeignKey to Flight, and we want to make queries on that other model, still filtering for cancelled=True.

Bart113
  • 29
  • 3

1 Answers1

1

CustomQuerySetManager allows you to easily add methods do QuerySets instead of manager itself, so you could write your cancelled() method and have it available everywhere, even in related models.

Flight.objects.cancelled()

It's chainable: Flight.objects.filter(...).cancelled().update(...)

It can be used in related models: Airport.flights.cancelled()

Quick example:

class Flight(models.Model):
    objects = CustomQuerySetManager()

    # Nested class definition, similar to the Meta class
    class QuerySet(QuerySet):  
        def cancelled(self):
            return self.filter(_cancelled=True)
Community
  • 1
  • 1
HankMoody
  • 3,077
  • 1
  • 17
  • 38