DJANGO:指的是id

DJANGO:指的是id,django,django-models,django-views,Django,Django Models,Django Views,这里有一点给了我一个问题:错误'QuerySet'对象没有属性'address' bdns = Business.objects.filter(name='slow') addx = bdns.address addr = Address.objects.get(id=addx) 我该怎么办 我的商业模式: class Business(models.Model): phone = PhoneNumberField() addr

这里有一点给了我一个问题:错误'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)

queryset是一个集合,即使该集合只包含一个元素。执行
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

queryset是一个集合,即使该集合只包含一个元素。执行
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
返回一个
QuerySet
(业务
对象的集合),您需要迭代以获取每个元素的地址

addr = Address.objects.get(id=addx)
应该有用

返回一个
QuerySet
(业务
对象的集合),您需要迭代以获取每个元素的地址

addr = Address.objects.get(id=addx)

应该可以了

@ellie请看我的编辑。一旦您有了业务,您就可以通过执行
dbns.Address
来访问地址实例。无需再查询Address类。@ellie请参阅我的编辑。一旦您有了业务,您就可以通过执行
dbns.Address
来访问地址实例。无需对Address类执行另一个查询。