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?

asked Jun 13, 2012 at 11:43
3
  • This is the standard method in Python (docs.python.org/library/functions.html#property) -- I'm just using the decorator style instead of explicitly calling property. Commented Jun 13, 2012 at 16:04
  • You mean Post(body="foo", summary="bar")?(note that body instead of title). This should work. Commented Jun 13, 2012 at 16:29
  • @okm I fixed that typo. It used to say Post(title="foo", summary="bar") which was an obvious typo. Commented Jun 20, 2013 at 20:27

1 Answer 1

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.

answered Jun 14, 2012 at 1:00
Sign up to request clarification or add additional context in comments.

2 Comments

Have you tried that? The code shows that its possible to assign property through kwargs since 5 years ago...
Oh, seems you are right – the constructor does support properties; this is in order to support GenericForeignKey. However, the other argument about QuerySets holds.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.