[英]Django foo_set doesnt work
I got stucked with Django (v1.9.4) a bit. 我有点沉迷于Django(v1.9.4)。 I have created two models, Foo and Bar:
我创建了两个模型,Foo和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 迁移它(sqlite3),片刻后意识到它应该是
foo instead of foo_id:
foo而不是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 我这次用foo再次迁移它,但即使经过这次修正后我也无法使用
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'
错误消息:异常类型:AttributeError异常值:'Foo'对象没有属性'bar_set'
It's not working because filter
returns a QuerySet
(which is a list), not an object. 它不起作用,因为
filter
返回一个QuerySet
(它是一个列表),而不是一个对象。 You need to use get
instead of filter
because get
returns an object. 您需要使用
get
而不是filter
因为get
返回一个对象。
f = Foo.objects.get(pk=1)
f.bar_set.all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.