Reputation: 9986
I was trying to create a dynamic property using the method decorator, the problem I'm having is that I want to use this field if the user hasn't save his/her own only. For example:
class Person(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.name
@property
def name(self):
return self.name if self.name else "John"
Basically, I want to return "John" if I don't find anything in the name fields. However, doing it this way, Django complains because self.name
is looking into the name function not the actual property.
maximum recursion depth exceeded while calling a Python object
Is there a way to refer to the real property or maybe some other way to accomplish this?
Upvotes: 1
Views: 2251
Reputation: 319
Is there a reason that you can't use a default? You can put a callable in there if you want something more interesting than a single value.
From the docs:
def name_default():
return "John"
name = models.CharField(max_length=100, default=name_default)
Upvotes: 1
Reputation: 1518
You should not duplicate names within single namespace. You can either rename your field from name
to _name
, since you are not going to expose it or give your property another name.
Actually, I can't see any way to get initial attribute name
. It seems like it totally overrides by property:
In [8]: 1 class A(object):
2 name = 0
3 @property
4 def name():
5 return self.name or 5
In [9]: A.__dict__
Out[9]:
<dictproxy {'__dict__': <attribute '__dict__' of 'A' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'A' objects>,
'name': <property at 0x7f50832736d8>}>
Upvotes: 2
Reputation: 55962
A simple way of doing this is to rename your accessor method/property:
class Person(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.name
def get_name(self):
return self.name if self.name else "John"
then when you have an instance:
person.get_name()
Upvotes: 4