开发者

DJANGO: referring to id

Here's the bit that's giving me an issue: error 'QuerySet' object has no attribute 'address'

        bdns = Business.objects.filter(name='slow')
        addx = bdns.address
        addr = Address.objects.get(id=addx)

What should I do?

My model for Business:

class Business(models.Model): 
    phone = PhoneNumberField()
    address = models.ForeignKey(Address)
    name = models.CharField(max_length=6开发者_运维问答4)


A queryset is a collection, even if that collection only contains one element. When you do Model.objects.filter(), it returns a queryset.

If you want to return a single object, use Model.objects.get().

So, for your purposes:

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


    bdns = Business.objects.filter(name='slow')

Returns you a QuerySet (the collection of Business objects) You need to iterate to get each element with address.

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

Should work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜