[英]'NoneType' object has no attribute 'add' in Django Models
我有下一個:'NoneType' object 沒有屬性'add'。 當我嘗試使用auction.winner.add(u) 向null 字段(null=True)添加一個值時,它給了我這個例外。 我正在使用 Django 模型,看起來幾乎不允許使用這種方法向 null 字段添加值。 有沒有辦法做到這一點?
我的模型.py:
class Bids(models.Model):
bid = models.IntegerField(max_length=64)
user_id2 = models.ForeignKey(User, on_delete = models.CASCADE, related_name="user_id2")
class Comments(models.Model):
comments = models.TextField(max_length=64)
user_id3 = models.ForeignKey(User, on_delete = models.CASCADE, related_name="user_id3")
class Categories(models.Model):
categories = models.CharField(max_length=64)
class Auction(models.Model):
title = models.CharField(max_length=64)
description = models.CharField(max_length=64)
starting_bid = models.IntegerField(max_length=64)
photo_url = models.CharField(max_length=64, blank=True, null=True)
category = models.ForeignKey(Categories, on_delete = models.CASCADE, related_name="category")
user_id = models.ForeignKey(User, on_delete = models.CASCADE, related_name="user_id")
winner = models.ForeignKey(User, blank=True, null=True, on_delete = models.CASCADE, related_name="winner")
bids = models.ManyToManyField(Bids, blank=True, related_name="bi")
comments = models.ManyToManyField(Comments, blank=True, related_name="co")
然后我的 function:
def win(request, auction_id):
if request.method == "POST":
auction = Auction.objects.get(pk=int(auction_id))
auction_bids = auction.bids.all()
j = 0
for i in auction_bids:
if i.bid > j:
j = i.bid
k = i.user_id2.id
else:
pass
u = User.objects.get(pk=int(k))
auction.winner.update(u)
更改winner_id
,然后保存拍賣。
def win(request, auction_id):
if request.method == "POST":
auction = Auction.objects.get(pk=int(auction_id))
auction_bids = auction.bids.all()
j = 0
for i in auction_bids:
if i.bid > j:
j = i.bid
k = i.user_id2.id
else:
pass
auction.winner_id = k
auction.save(update_fields=["winner"])
檢查它是否是 null 然后將其初始化為獲勝用戶的 id。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.