0

I have a (duplicate detection) query in Django that I want to apply for several models:

Cooperation.objects.values('seo__slug').annotate(count=Count('id')).values('seo__slug).filter(count__gt=1)
Article.objects.values('seo__slug').annotate(count=Count('id')).values('seo__slug).filter(count__gt=1)
City.objects.values('seo__slug').annotate(count=Count('id')).values('seo__slug).filter(count__gt=1)

Is there a coding concept so that I can do this in a loop. e.g (Pseudo Code, this below is not working)

information_objects = ['Cooperation', 'Article', 'City']
for obj in information_objects:
  obj.objects.values('seo__slug').annotate(count=Count('id')).values('seo__slug).filter(count__gt=1)

I hope I can get my question across. If anybody can tell me if this concept is supported in Django please let me know.

1 Answer 1

1

You can make the list contain the actual classes, then your code will work:

information_objects = [Cooperation, Article, City]

If you absolutely need to get them based on strings, you can get the classes from globals():

information_objects = [globals()[name] for name in ('Cooperation', 'Article', 'City')]

or use getattr if they are in a specific module:

information_objects = [getattr(the_module, name) for name in ('Cooperation', 'Article', 'City')]
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.