I am using django 2.0.8 and Python 3.5. I have written a base class which encapsulates behavior in a base class.
When using the interface in the child class, I find that I have to pass the object of the child class to the parent - which is not only ugly, is error prone.
I do not want to use composition (instead of an interface), because AFAIK fields in django models are saved to the DB - that aside, I prefer the sub classing approach, since all the functionality can remain in the base class.
Is there any way I can (in the parent class), find/obtain the instance (or at least the name of the class and it's id) that invoked the method call?
Here is my code:
class Likeable(models.Model):
likes = GenericRelation(Like)
def action_is_permissible(self, actionable_object, actor):
ct = ContentType.objects.get_for_model(actionable_object)
object_id = actionable_object.id
found_objects = Like.objects.filter(content_type=ct, object_id=object_id, liker=actor)
return ((len(found_objects) == 0), ct, object_id, found_objects)
def add_like(self, actionable_object, actor):
can_add, ct, object_id, found_objects = self.action_is_permissible(actionable_object, actor)
if can_add:
like = self.likes.create(content_type=ct, object_id=object_id, liker=actor)
else:
# do nothing
return
class Meta:
abstract = True
class Foo(Likeable):
name = models.CharField(max_length=255,default='')
objects = models.Manager()
Example use (imports omitted)
foo = Foo.objects.get(id=1)
p = User.objects.get(id=1)
foo.add_like(foo, p) # <- nasty API calling convention