简体   繁体   中英

Filter a DJango ContentType queryset to only include models that have a specific method

How can I filter a ContentType queryset to only include models that have a specific method?

class myModel(models.Model):
    ...
    def mySpecificMethod:
        ...

What can I put in ??? to get all models where mySpecificMethod exists?

ContentType.objects.filter(???)

I think is more proper to filter it by loop.

If you intend to get a result of type QuerySet , you can simply loop them, then get the ID list, then use pk__in parameter to filter it.

ContentType.objecst.filter(
    pk__in=[
        ct.pk for ct ContentType.objects.all() 
        if content_type_has_method(ct, 'method_name')
    ]
)

So, you have reduced this question to write a method:

def content_type_has_method(ct, method_name):
    ...

And I think that is simpler for you, good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM