12

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?

futuraprime
  • 5,468
  • 7
  • 38
  • 58
  • This is the standard method in Python (http://docs.python.org/library/functions.html#property) -- I'm just using the decorator style instead of explicitly calling `property`. – futuraprime Jun 13 '12 at 16:04
  • You mean `Post(body="foo", summary="bar")`?(note that `body` instead of `title`). This should work. – okm Jun 13 '12 at 16:29
  • @okm I fixed that typo. It used to say `Post(title="foo", summary="bar")` which was an obvious typo. – Buttons840 Jun 20 '13 at 20:27

1 Answers1

14

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.

koniiiik
  • 4,240
  • 1
  • 23
  • 28
  • Have you tried that? [The code](https://github.com/django/django/commit/90acc8ff7e1b27b5c2f7cd5a2440d94d5fa22445#L0R153) shows that its possible to assign property through `kwargs` since 5 years ago... – okm Jun 14 '12 at 03:44
  • Oh, seems you are right – the constructor does support properties; this is in order to support `GenericForeignKey`. However, the other argument about QuerySets holds. – koniiiik Jun 20 '12 at 13:52