R0b0tn1k
R0b0tn1k

Reputation: 4306

Django: Getting category from add in view

I have this view, right:

def thisviewright(request,pk):
   theadd = adds.objects.filter(id=pk)
   theaddlist = adds.objects.filter(category=add.category)
   return render_to_response..

And i'm trying to get the category so i display all other adds that have the same category. As i'm not passing the category from a URL, i have to get it from the add, who's ID i am passing.

But i'm getting an error: Queryset has no attribute Category

The model is as follows:

class adds(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey('categories')
...

class categories(models.Model):
title = models.CharField(max_length=255)

So long question short, how do i get the related adds from the same category by using the category from the object i'm passing?

Upvotes: 0

Views: 47

Answers (1)

TimD
TimD

Reputation: 1381

In the first line of the view, you're returning a queryset, not an object. While this queryset will contain only one objec, others constructed using a filter will have multiple members.

To return an object as opposed to a queryset with that line, use either of the following lines:

theadd = adds.objects.get(id=pk)
theadd = adds.objects.filter(id=pk)[0]

You should only ever use the first on unique indexed properties (i.e. id), as it will fail with an error if there is more than one object that matches the criterion.

Upvotes: 1

Related Questions