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

mgPePe picture mgPePe · Nov 30, 2010 · Viewed 27.1k times · Source

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)

Answer

Daniel DiPaolo picture Daniel DiPaolo · Nov 30, 2010

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.