Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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)

like image 513
mgPePe Avatar asked Nov 30 '10 22:11

mgPePe


2 Answers

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.

like image 192
Daniel DiPaolo Avatar answered Oct 15 '22 22:10

Daniel DiPaolo


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

like image 25
Ignacio Vazquez-Abrams Avatar answered Oct 15 '22 23:10

Ignacio Vazquez-Abrams