这是给我一个问题的一点:错误'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)
答案 0 :(得分:3)
查询集是一个集合,即使该集合只包含一个元素。执行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
答案 1 :(得分:0)
bdns = Business.objects.filter(name='slow')
返回QuerySet
(Business
个对象的集合)您需要迭代以获取具有地址的每个元素。
addr = Address.objects.get(id=addx)
应该工作