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)
filterreturns aQuerySet(as you may have guessed), you want to dogetinsteadIf the
Subjectdoes not exist you will get aSubject.DoesNotExistexception. There’s also theget_object_or_404shortcut indjango.shortcutsthat 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.