Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models and Python properties

I've tried to set up a Django model with a python property, like so:

class Post(models.Model):
    _summary = models.TextField(blank=True)
    body = models.TextField()

    @property
    def summary(self):
        if self._summary:
            return self._summary
        else:
            return self.body

    @summary.setter
    def summary(self, value):
        self._summary = value

    @summary.deleter
    def summary(self):
        self._summary = ''

So far so good, and in the console I can interact with the summary property just fine. But when I try to do anything Django-y with this, like Post(title="foo", summary="bar"), it throws a fit. Is there any way to get Django to play nice with Python properties?

like image 603
futuraprime Avatar asked Jun 13 '12 11:06

futuraprime


1 Answers

Unfortunately, Django models don't play very nice with Python properties. The way it works, the ORM only recognizes the names of field instances in QuerySet filters.

You won't be able to refer to summary in your filters, instead you'll have to use _summary. This gets messy real quick, for example to refer to this field in a multi-table query, you'd have to use something like

User.objects.filter(post___summary__contains="some string")

See https://code.djangoproject.com/ticket/3148 for more detail on property support.

like image 81
koniiiik Avatar answered Oct 19 '22 04:10

koniiiik