mgPePe
mgPePe

Reputation: 5907

'QuerySet' object has no attribute ERROR, trying to get related data on ManyToMany fields

i have the following models:

class Tag(models.Model):
    tag_name = models.CharField(max_length=250)
    tagcat = models.ForeignKey('TagCat')

class Subject(models.Model):
    user = models.ManyToManyField(User)
    tags = models.ManyToManyField(Tag)

class TagCat(models.Model):
    cat_name = models.CharField(max_length=100)

So i have a subject, that has a tag. I want to loop the subjects and their appropriate tags, so I am trying to construct the right view. So far, I have:

def home(request):
    user1 = Subject.objects.filter(id=1)
    print(user1.tags.all())

I would expect to get the tags of the user through this print statement, but instead I get error

'QuerySet' object has no attribute 'tags'

How would I be getting the 'Subject' objects with their respective tags and pass them to template?

(Ideally all subjects. I did it with just one here, to simplify for the process of troubleshooting)

Upvotes: 19

Views: 29997

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798814

QuerySet.get() will either return a single model as given by the criteria passed by it, or it will raise an exception.

Upvotes: 3

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

filter returns a QuerySet (as you may have guessed), you want to do get instead

user1 = Subject.objects.get(id=1)

If the Subject does not exist you will get a Subject.DoesNotExist exception. There's also the get_object_or_404 shortcut in django.shortcuts that is useful if you're simply grabbing an object that is to be displayed in some way and you want to return a 404 if it is not available.

Upvotes: 34

Related Questions