我不确定如何解决这个问题。我尝试将 highest_bid 转换为 float :
highest_bid = float(Bid.objects.filter(id=bid_item.id).aggregate(Max('bid_input')))
但这也产生了一个错误,因为字典不能以这种方式转换为 float 。所以我不确定如何解决这个问题。我正在尝试建立一个拍卖网站,如果用户的出价低于上市起拍价且低于所有已出价的最高价,我希望拒绝该出价。
错误
Internal Server Error: /listing/2/bid
Traceback (most recent call last):
File "C:\Python\Python385\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Python\Python385\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\sarah\Desktop\commerce\auctions\views.py", line 157, in placebid
if bidform.cleaned_data['bid_input'] < listing.start_price and bidform.cleaned_data['bid_input'] <= highest_bid:
TypeError: '<=' not supported between instances of 'decimal.Decimal' and 'dict'
[08/Oct/2020 13:59:48] "POST /listing/2/bid HTTP/1.1" 500 62598
views.py
def placebid(request, id):
listing_bid = get_object_or_404(Listing, id=id)
highest_bid = Bid.objects.filter(id=id).aggregate(Max('bid_input'))
listing = Listing.objects.get(pk=id)
if request.method == "POST":
bidform = BidForm(request.POST)
if bidform.is_valid():
if bidform.cleaned_data['bid_input'] < listing.start_price and bidform.cleaned_data['bid_input'] <= highest_bid:
return render(request, "auctions/listingPage.html", {
"listing": listing,
"error": "Make sure your bid is greater than the start price and current highest bid"
})
else:
listing_bid.bid_input = bidform.cleaned_data['bid_input']
listing_bid.bidder = request.user
listing_bid.bid_item = listing
listing_bid.time = timezone.now()
listing_bid.save()
messages.success(request, 'Bid placed succesfully')
return HttpResponseRedirect(reverse("listing", args=(id,)))
else:
return render(request, "auctions/listingPage.html", {
"bidform": bidform })
else:
bidform = BidForm()
return render(request, "auctions/listingPage.html", {
"bidform": bidform })
如果我需要包含更多详细信息,请告诉我。
编辑添加:models.py
class Listing(models.Model):
class NewManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(status='active')
options = (
('active', 'Active'),
('closed', 'Closed'),
)
title = models.CharField(max_length=64)
description = models.TextField(max_length=64)
start_price = models.DecimalField(max_digits=9, decimal_places=2, validators=[MinValueValidator(0.99)])
image = models.URLField(max_length=200, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="listings")
lister = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True, related_name="lister_user")
date_added = models.DateTimeField(default=timezone.now)
status = models.CharField(max_length=10, choices=options, default="active")
winner = models.ForeignKey('Bid', on_delete=models.CASCADE, null=True, related_name="bid_winner")
favourites = models.ManyToManyField(User, related_name="favourite", default=None, blank=True)
objects = models.Manager()
listingmanager = NewManager()
def __str__(self):
return f"{self.title} ({self.pk}, £{self.start_price}, {self.lister})"
class Bid(models.Model):
bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidders")
bid_item = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bid_items", default=None)
bid_input = models.DecimalField(max_digits=9, decimal_places=2, default=None)
time = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.bidder}, bid amount: {self.bid_input}"
编辑添加:更新 views.py
def placebid(request, id):
listing_bid = get_object_or_404(Listing, id=id)
highest_bid = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] or Decimal('0')
listing = Listing.objects.get(pk=id)
if request.method == "POST":
bidform = BidForm(request.POST)
if bidform.is_valid():
if bidform.cleaned_data['bid_input'] < listing.start_price and bidform.cleaned_data['bid_input'] <= highest_bid:
return render(request, "auctions/listingPage.html", {
"listing": listing,
"error": "Make sure your bid is greater than the start price and current highest bid"
})
else:
newbid = bidform.save(commit=False)
newbid.bidder = request.user
newbid.bid_input = bidform.cleaned_data['bid_input']
newbid.bid_item = listing_bid
newbid.time = timezone.now()
newbid.save()
messages.success(request, 'Bid placed succesfully')
return HttpResponseRedirect(reverse("listing", args=(id,)))
else:
return render(request, "auctions/listingPage.html", {
"bidform": bidform })
else:
bidform = BidForm()
return render(request, "auctions/listingPage.html", {
"bidform": bidform })
最佳答案
highest_bid
是一个将聚合名称映射到值的字典,因此例如 { 'bid_input__max': Decimal('14.25') }
,您可以因此通过下标从字典中解包值:
highest_bid = Bid.objects.filter(
id=id
).aggregate(Max('bid_input'))<b>['bid_input__max']</b>
但这可能不会给您预期的值(value)。您过滤 id=id
,这意味着查询集跨越 一个 记录。您可能希望过滤 bid_item_id=id
或类似内容:
highest_bid = Bid.objects.filter(
<b>bid_item_id=id</b>
).aggregate(Max('bid_input'))['bid_input__max']
根据您的评论,可能还没有出价。在这种情况下,它将返回一个 None
。我们可以使用零代替:
highest_bid = Bid.objects.filter(
bid_item_id=id
).aggregate(Max('bid_input'))['bid_input__max'] <b> or Decimal('0')</b>
关于python - 类型错误 : '<=' not supported between instances of 'decimal.Decimal' and 'dict' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64263298/