0

Is there a way to do the following in a single line with a django query?

providers_with_no_contacts = []
for provider in Provider.objects.all():
    if not provider.userprofile_set.all():
        provider_with_no_contacts.append(provider)

Or a better way than this?

providers_with_no_contacts = [provider for provider in Provider.objects.all() 
                               if not provider.userprofile_set.all()]

2 Answers 2

1
Provider.objects.filter(userprofile__isnull=True)
Sign up to request clarification or add additional context in comments.

Comments

0

providers_with_no_contacts = Provider.objects.filter(userprofile_set=None)

2 Comments

That didn't work. Perhaps it is because userprofile is a M2M field?
Try: .filter(userprofile__isnull=True). Works whether the field is a foreign key or M2M.

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.