【问题标题】:access value in a model in Django在 Django 中访问模型中的值
【发布时间】: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 对象。

标签: python django


【解决方案1】:

您正在尝试访问QuerySetbid_value 属性,而不是模型。

您正试图从列表中获取值。由于Bids 模型的auction 属性是ForeignKeyField,因此查询返回一个列表,而不是单个实例。你需要从Bids.objects获取最大值

if request.method == "POST":
        bid = Bids.objects.filter(auction=item_id).aggregate(Max('bid_value'))['bid_value__max']

        .....

【讨论】:

    【解决方案2】:

    你的代码为什么失败的线索当然是在错误中。

    “/item/2 'QuerySet' 对象的 AttributeError 没有属性 'bid_value'”

    你的错误在这里:

    bid = Bids.objects.filter(auction=item_id).bid_value
    

    使用 Bids.objects.filter(auction=item_id) 您正在创建一个 Queryset 对象。 我喜欢this explanation from djangogirls: “QuerySet 本质上是给定模型的对象列表。QuerySet 允许您从数据库中读取数据,对其进行过滤和排序。”

    您需要访问模型的 bid_value 属性。因此,一种方法是获取查询集返回的第一个值:

    bid = Bids.objects.filter(auction=item_id).first().bid_value
    

    更好的方法是检查对象是否存在,然后访问 bid_value 属性:

    bid = Bids.objects.filter(auction=item_id).first()
    if bid:
        bid = bid.bid_value
    

    学习愉快! :)

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 2020-05-25
      • 2011-05-15
      • 2019-03-26
      • 1970-01-01
      • 2017-03-07
      • 2015-01-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多