[英]Django QuerySet is too redundant
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: 因此,出于我自己的理智,我有一个问题……我制作了一个API,但由于需要在多个不同的对象上执行相同的操作,因此这是非常多余的:
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. 对于API,名称中的单词总是用下划线分隔,并且将我需要访问的表中的单词作为第一个单词。 Is there any way to make it so I don't have to be so redundant?
有没有办法做到这一点,所以我不必这么多余?
If I understand the question now, so: 如果我现在理解了这个问题,那么:
def field_by(self, field_name, user):
return self.filter(**{field_name + '__user': user})
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):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.