Reputation: 17869
So I have an issue simply for my own sanity...I have made an API, but it is extremely redundant since the same operations need to be done on multiple different objects:
def seen_by(self,user):
return self.filter(seen__user=user)
def created_by(self,user):
return self.filter(created__user=user)
#and the list goes on
For the API, the names will always have words be separated by an underscore and have the word of the table I need to get to as the first word. Is there any way to make it so I don't have to be so redundant?
Upvotes: 0
Views: 105
Reputation: 1082
If I understand the question now, so:
def field_by(self, field_name, user):
return self.filter(**{field_name + '__user': user})
Upvotes: 2
Reputation: 121
You probably want to create an abstract model and have your models inherit it.
class Base(models.Model):
def seen_by(self, user):
return self.seen.get(user=user)
class Meta:
abstract = True
class ChildModel(Base):
...
Upvotes: 1