Prpaa
Prpaa

Reputation: 245

Django foo_set doesnt work

I got stucked with Django (v1.9.4) a bit. I have created two models, Foo and Bar:

class Foo(models.Model):
    name = models.CharField(max_length=100)
class Bar(models.Model):
    foo_id = models.ForeignKey(Foo, on_delete=models.CASCADE)
    title = models.CharField(max_length=300)

migrate it (sqlite3) and few moments later realized that it should be

foo instead of foo_id:

foo = models.ForeignKey(Foo, on_delete=models.CASCADE)

I migrated it again, with foo this time, but even after this correction I wasn't able to use

f = Foo.objects.filter(pk=1) 
f.bar_set.all()

Is there a way to deal with this?

Edit. Error msg: Exception Type: AttributeError Exception Value:'Foo' object has no attribute 'bar_set'

Upvotes: 1

Views: 360

Answers (1)

xyres
xyres

Reputation: 21799

It's not working because filter returns a QuerySet (which is a list), not an object. You need to use get instead of filter because get returns an object.

f = Foo.objects.get(pk=1)
f.bar_set.all()

Upvotes: 3

Related Questions