以下是我的三种型号:
class User(AbstractUser):
pass
class Category(models.Model):
Name = models.CharField(max_length=20)
class Listing(models.Model):
Title = models.CharField(max_length=20)
Description = models.TextField()
StartingBid = models.IntegerField()
Category = models.ManyToManyField(Category, verbose_name="Categories")
Image = models.URLField()
CurrentBid = models.IntegerField()
Author = models.ForeignKey(User, on_delete=models.CASCADE)
Close = models.BooleanField()
这是将我带到所需视图的url:
path("<str:user>/<str:name>", views.name, name="name"),
最后是名称视图:
def name(request, user, name):
try:
l = Listing.objects.get(Title=name)
except Listing.DoesNotExist:
l = None
try:
**bid = Bid.objects.get(Bidder=user, Item=name)**
except Bid.DoesNotExist:
bid = None
if l.CurrentBid == bid.Value and l.Close:
won = True
else:
won = False
if l.Author == user:
owner = True
else:
owner = False
watchlist = Watchlist.objects.all()
if name in watchlist:
added = True
else:
added = False
return render(request, "auctions/name.html", {
"item": l,
"added": added,
"form_bid": BidForm(),
"m": "",
"owner": owner,
"comments": Comments.objects.filter(Item=name),
"won": won
})
这就是问题发生的地方:
bid = Bid.objects.get(Bidder=user, Item=name)
错误消息:
字段"id"需要一个数字,但得到了"admin"。(admin是用户名(
我知道问题是什么,但我不知道该怎么办。类出价的投标人属性是类用户的外键
有人能告诉我怎么做对吗?
path("<str:user>/<str:name>", views.name, name="name")
错误告诉你";嘿,Bidder
应该是一个int(它是一个外键(,而你给了我一个字符串"。我相信你可以给它id
或者ForeignKey引用的模型的一个实例。你在这里有用户的用户名,所以你可以进行
bidder = User.objects.get(username=user)
注意,Item
参数也会有同样的问题,因为我假设它是引用Listing
实例的ForeignKey?然后,您需要在此处传递l
变量。最终:
bid = Bid.objects.get(Bidder=bidder, Item=l) # `bidder` and `l` are instances of `User` and `Listing`
最好在这里设置使用主键的路径,并使用.get(pk=...)
获取每个模型的实例:
path("<int:user_id>/<int:listing_id>", views.name, name="name")