algorithmicCoder
algorithmicCoder

Reputation: 6799

Django select many to many field without raising error

Im' new to Django. I have an Author object (author) and an entry ID (entry_id) and I want to find out whether author is an author of an Entry.

Here's Entry:

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    authors = models.ManyToManyField(Author)

If I do

foo = Entry.objects.get(pk=entry_id, authors = author)

I get an error when the author is not an author of an entry.

What is the simpler way to do this? ultimately i just want a yes/no answer to the question of whether the author is an author for that entry. I want a valid object and not an error when the answer is no.

Thanks!

Upvotes: 1

Views: 143

Answers (5)

César
César

Reputation: 10119

According to your question specifications:

  1. ultimately i just want a yes/no answer to the question of whether the author is an author for that entry.

    Use exists()

    From the docs:

    Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

    It will not raise any errors, it will return just True or False so you can use it inside an if statement. You can try something like:

    if Entry.objects.filter(pk=entry_id, authors=author).exists():
        # Magic here
    

    Note that I'm using filter() instead of get() because exists() is a QuerySet method (get() returns an object not a QuerySet)

  2. I want a valid object and not an error when the answer is no.

    Using @nabucosound approach may be what you want.

Upvotes: 2

nabucosound
nabucosound

Reputation: 1293

You say you want a "valid object" so I assume you need this object to perform something with it. Thus, the lack of the object should carry performing something else, right? The most common validation done with the Django ORM for this scenario is the try/except:

try:
    foo = Entry.objects.get(pk=entry_id, authors=author)
except Entry.DoesNotExist:
    # Do something when object does not exist
    pass
else:
    # Do something with your foo object

There is nothing wrong and, in fact, Python encourages this style:

http://en.wikipedia.org/wiki/Duck_typing#In_Python

Upvotes: 1

Ted
Ted

Reputation: 12318

count = Entry.objects.filter(pk=entry_id, authors = author).count()

if count > 0:
  #The author is an author

Upvotes: 0

Raunak Agarwal
Raunak Agarwal

Reputation: 7238

You could simply check the authors of the Entry object...Try this

entry = Entry.objects.get(id=entry_id)
is_author = True

try:
   entry.authors.get(id=author.id)
except:
  is_author=False

Upvotes: 0

second
second

Reputation: 28655

maybe something like

entry = Entry.objects.get(pk=entry_id)
author in entry.authors.all()  # True or False

Upvotes: 0

Related Questions