【发布时间】:2020-07-16 18:29:27
【问题描述】:
我一周前开始学习 django,我正在尝试从 django 中的模型获取bid_value,但它返回此错误:
/item/2 'QuerySet' 对象的 AttributeError 没有属性 “出价”
我尝试了几种方法,但都没有成功
models.py:
class Auction_listings(models.Model):
product_image = models.CharField(max_length=500)
product_title = models.CharField(max_length=40)
product_description = models.CharField(max_length=200)
product_category = models.CharField(max_length=20, default="others")
product_price = models.FloatField()
is_closed = models.BooleanField(default=False)
username = models.CharField(max_length=64)
post_date = models.DateField(auto_now_add=True)
def __str__(self):
return f"{self.product_title}"
class Bids(models.Model):
auction = models.ForeignKey(Auction_listings, on_delete=models.CASCADE)
username = models.CharField(max_length=64)
bid_value = models.FloatField()
views.py:
def add_bid(request, item_id):
username = None
if request.user.is_authenticated:
username = request.user.username
if request.method == "POST":
bid = Bids.objects.filter(auction=item_id).bid_value
new_bid_value = float(request.POST.get("bid"))
if new_bid_value > float(bid):
new_bid = Bids(auction=item_id, username=username, bid_value=new_bid_value)
new_bid.save()
else:
return render(request, "auctions/error.html", {
"error": "your bid is lower than the current bid..."
})
def view_item(request, id):
item_id = Auction_listings.objects.get(pk=id)
add_bid(request, item_id)
try:
bid = Bids.objects.get(auction=item_id)
return render(request, "auctions/item.html", {
"auctions": item_id,
"bid": bid
})
except:
return render(request, "auctions/item.html", {
"auctions": item_id,
})
谢谢你
【问题讨论】:
-
Bids.objects.filter(auction=item_id).bid_value没有意义,因为这是Bids对象的集合(集合),而不是单个Bid对象。