我有一个模板标签,可以通过标签返回所有相关对象,但如果查询集查看同一模型,我想排除 self
def get_related_projects(obj):
published_projects = Project.objects.published()
first_obj = published_projects.first()
if first_obj.__class__ == obj.__class__:
published_projects = published_projects.exclude(pk=obj.pk)
是否有更多的pythonic方式来比较两个模型?
答案 0 :(得分:1)
您可以使用type
获取模型类,然后使用is
快速检查模型类的相同性:
if type(first_obj) is type(obj):
published_projects = published_projects.exclude(pk=obj.pk)
答案 1 :(得分:1)
或者做:
if isinstance(first_obj, class):
published_projects = published_projects.exclude(pk=obj.pk)
如果您只想知道与QuerySet关联的模型类,请执行以下操作:
def get_related_projects(obj):
published_projects = Project.objects.published()
if isinstance(published_projects.model, ModelClassHere):
published_projects = published_projects.exclude(pk=obj.pk)