,python,django,django-models"/>

首页 > 解决方案 > 字段 'id' 需要一个数字,但得到了

问题描述

这是我第一次使用模型创建 Django 网站,并且在我第一次尝试将数据插入到我的表中时,我遇到了这个错误。

我的模型如下:

class User(AbstractUser):
    pass
    #https://docs.djangoproject.com/en/3.1/topics/auth/default/

class Listing(models.Model):
    listingID = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="listID")
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="myListing", null=True)
    watchers = models.ManyToManyField(User, blank=True, related_name="watchlist")

    title = models.CharField(max_length=30)
    description = models.TextField()
    creation_date = models.DateField(auto_now=True)
    img_url = models.URLField()
    active = models.BooleanField(default=True)

    def __str__(self):
        return f"{self.title}"

class Bid(models.Model):
    listing = models.ForeignKey(Listing, on_delete=models.SET_NULL, related_name="bidsMadeOnMe", null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name="myBids", null=True)

    price = models.FloatField()
    creation_date = models.DateField(auto_now=True, null=True)

    def __str__(self):
        return f"Bid={self.price}"

处理表单提交的视图是这个:

@login_required
def create_listing(request):
    if request.method == "POST":
        user = User.objects.get(username=request.user.username)
        l = Listing(created_by=user, 
                    title=request.POST["title"], 
                    description=request.POST["desc"], 
                    # https://stackoverflow.com/questions/12176585/handling-dates-over-request-get
                    creation_date=models.DateTimeField(auto_now_add=True), 
                    img_url=request.POST["image_url"]
                    )
        l.save()

        b = Bid(l, 
                user, 
                request.POST["initial_bid"], 
                models.DateTimeField(auto_now_add=True)
                )
        b.save()

    return render(request, "auctions/index.html")

我知道问题在于我添加数据的方式,但我无法修复它。有人可以给我一些光吗?

标签: pythondjangodjango-models

解决方案


你的问题(嗯,实际上是几个)是这样的:

b = Bid(l, user, request.POST["initial_bid"], models.DateTimeField(auto_now_add=True))

您正在通过位置参数而不是关键字参数构造模型实例。可以这样做,但是添加到 Bid 模型中的不可见“id”列是第一个参数。

在 Django 中,我们从不构建这样的模型,但总是使用关键字参数,因此我们不依赖于字段顺序:

b = Bid(listing=l, user=user, ...))

一旦你解决了这个问题,你的下一个问题就是日期字段。

不要将字段分配给模型实例。字段是类声明,它们不属于实例。字段描述一个类(=一个模型),期望什么样的数据。在实例上,您分配该数据。

在这种情况下,您对该字段的定义在模型上是错误的,并且在您甚至不应该分配它的实例上 - 它会被自动填充。

总的来说,感觉就像你没有读过Django 的教程或者没有完全理解这些概念。我建议你通过它。


推荐阅读