简体   繁体   中英

django - Best way to compare two models?

I have a templatetag that returns all related objects through their tags, but I want to exclude self if the queryset looks through the same model

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)

Is there a more pythonic way to compare two models?

You can use type to get the model classes and then use is to do a quick check on the sameness of the model classes:

if type(first_obj) is type(obj):
     published_projects = published_projects.exclude(pk=obj.pk)

Or do:

if isinstance(first_obj, class):
    published_projects = published_projects.exclude(pk=obj.pk)

If you just want to know the model class associated with a QuerySet simply do:

def get_related_projects(obj):
    published_projects = Project.objects.published()

    if isinstance(published_projects.model, ModelClassHere):
        published_projects = published_projects.exclude(pk=obj.pk)

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