I am trying to set a class attribute dynamically, by performing an operation on another class attribute. My code goes like this
class LastActionModel(BaseModel):
"""
Provides created_by updated_by fields if you have an instance of user,
you can get all the items, with Item being the model name, created or updated
by user using user.created_items() or user.updated_items()
"""
created_by = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True,
related_name = lambda self:'%s_%s' %('created', \
self._meta.verbose_name_plural.title().lower())
)
updated_by = models.ForeignKey(
settings.AUTH_USER_MODEL, blank=True, null=True,
related_name = lambda self:'%s_%s' %('updated', \
self._meta.verbose_name_plural.title().lower())
)
class Meta:
abstract = True
This is to dynamically set the related name so that for a class Item, and a User 'user', i can easily call user.created_items.all().
This is giving me the error
super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only)
File "/home/pywebapp/venv/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 113, in contribute_to_class
'app_label': cls._meta.app_label.lower()
TypeError: Error when calling the metaclass bases
unsupported operand type(s) for %: 'function' and 'dict'
where i am going wrong?
the answer was pretty simple, as per docs
class LastActionModel(BaseModel):
"""
Provides created_by updated_by fields if you have an instance of user,
you can get all the items, with Item being the model name, created or updated
by user using user.created_items() or user.updated_items()
"""
created_by = models.ForeignKey(
'users.User', blank=True, null=True,
related_name = 'created_%(class)ss'
)
updated_by = models.ForeignKey(
'users.User', blank=True, null=True,
related_name = 'updated_%(class)ss'
)
class Meta:
abstract = True
hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With