过滤 DJango ContentType 查询集以仅包含具有特定方法的模型
Filter a DJango ContentType queryset to only include models that have a specific method
如何过滤 ContentType
查询集以仅包含具有特定方法的模型?
class myModel(models.Model):
...
def mySpecificMethod:
...
我可以在 ???
中输入什么来获取存在 mySpecificMethod
的所有模型?
ContentType.objects.filter(???)
我觉得循环过滤比较合适
如果你打算得到QuerySet
类型的结果,你可以简单地循环它们,然后得到ID列表,然后使用pk__in
参数过滤它。
ContentType.objecst.filter(
pk__in=[
ct.pk for ct ContentType.objects.all()
if content_type_has_method(ct, 'method_name')
]
)
所以,你把这个问题简化为写了一个方法:
def content_type_has_method(ct, method_name):
...
而且我认为这对您来说更简单,祝您好运!
如何过滤 ContentType
查询集以仅包含具有特定方法的模型?
class myModel(models.Model):
...
def mySpecificMethod:
...
我可以在 ???
中输入什么来获取存在 mySpecificMethod
的所有模型?
ContentType.objects.filter(???)
我觉得循环过滤比较合适
如果你打算得到QuerySet
类型的结果,你可以简单地循环它们,然后得到ID列表,然后使用pk__in
参数过滤它。
ContentType.objecst.filter(
pk__in=[
ct.pk for ct ContentType.objects.all()
if content_type_has_method(ct, 'method_name')
]
)
所以,你把这个问题简化为写了一个方法:
def content_type_has_method(ct, method_name):
...
而且我认为这对您来说更简单,祝您好运!