Rushikesh Sabde
Rushikesh Sabde

Reputation: 1626

Reverse Relationship in django 'QuerySet' object has no attribute 'name'

I have two models called car and producer. The two models have many to one relation between them.

class Producer(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class Car(models.Model):
    name = models.CharField(max_length=20)
    producer = models.ForeignKey(Producer, on_delete=models.CASCADE)

    def __str__(self):
        return self.name here

When i try to query the reverse relationship.

Producer.objects.filter(car__name='Mini')

then it return a queryset object

<QuerySet [<Producer: BMW>]>

when i try to assign the queryset object to a variable and fetch the name field result then it gives error.

obj1 = Producer.objects.filter(car__name='Mini')
    In [6]: obj1.name                                                                                                                                                                   
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-5155cb2773b4> in <module>
----> 1 obj1.name

AttributeError: 'QuerySet' object has no attribute 'name'

what could be the reason for this error

Upvotes: 3

Views: 2807

Answers (2)

Sergey Pugach
Sergey Pugach

Reputation: 5669

Queryset is a list of objects, not a single object.

So you can do:

obj1 = Producer.objects.filter(car__name='Mini').first(). # <- get first
In [6]: obj1.name  

or in case you have to handle multiple.

for obj in obj1:
    print(obj.name)
    # do your logic

Upvotes: 1

When do you use get() Django return an object and you can get the variables of that object, for example obj1.name, but when you use filter, Django return a Queryset, you have to iterate the queryset with a for:

mini_producers = Producer.objects.filter(car__name='Mini')

for producer in mini_producers:
    print(producer.name)

Upvotes: 2

Related Questions