这里有一个问题:错误'QuerySet‘对象没有'address’属性
bdns = Business.objects.filter(name='slow')
addx = bdns.address
addr = Address.objects.get(id=addx)
我该怎么办?
我的商业模式:
class Business(models.Model):
phone = PhoneNumberField()
address = models.ForeignKey(Address)
name = models.CharField(max_length=64)
发布于 2011-05-23 11:00:20
查询集是一个集合,即使该集合只包含一个元素。当您执行Model.objects.filter()
时,它会返回一个查询集。
如果您想返回单个对象,请使用Model.objects.get()
。
所以,为了你的目的:
bdns = Business.objects.filter(name='slow') # returns a collection
b = dbns[0] # get the first one
the_address = b.address # the address
# or...
try:
bdns = Business.objects.get(name='slow') # get single instance
except Business.DoesNotExist:
bdns = None # instance didnt exist, assign None to the variable
except Business.MultipleObjectsReturned:
bdns = None # the query returned a collection
if bdns is not None:
the_address = bdns.address
# the_address is an instance of an Address, so no need to do the lookup with the id
print the_address.id # 7
print the_address.street # 17 John St
print the_address.city # Melbourne
发布于 2011-05-23 11:00:48
bdns = Business.objects.filter(name='slow')
返回一个QuerySet
( Business
对象的集合),您需要迭代以获取每个具有address的元素。
addr = Address.objects.get(id=addx)
应该行得通
https://stackoverflow.com/questions/6096252
复制相似问题