我正在使用 Django createview 在拍賣網站中創建投標項目。createview 將創建新對象,但它會創建一個沒有相應外鍵的額外對象實例。我正在使用 @staticmethod 來確定提交的出價是否確實是最高出價,然后在相關列表中創建。如果您能指出我做錯了什么,請提前致謝。models.pyclass Bid(TimeStampMixin): """model representing bid obj""" auction = models.ForeignKey( Listing, on_delete=models.SET_NULL, related_name='offer', null=True) bidder = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='bid_user') amount = models.PositiveIntegerField() objects = BidQuerySet.as_manager() def __str__(self): return f"{self.amount} in Listing No: {self.auction.id}" class Meta: ordering = ['amount'] @staticmethod def high_bid(auction, bidder, bid_amount): """util method to ascertain highest bid in auction then create in related auction obj :param auction---listing being bid on, bid__auction :param bidder---user bidding :param amount--- current highest bid """ ###error checks, is auction running? is current bid less than start bid? etc if bid_amount < auction.start_bid: return if (auction.highest_offer and bid_amount < auction.highest_offer.amount): return if bidder.id is auction.user.id: raise PermissionDenied ##after checks create highest bid object in listing model new_high_bid = Bid.objects.create( auction= auction, bidder = bidder, amount = bid_amount )
1 回答

開滿天機
TA貢獻1786條經驗 獲得超13個贊
從 form_valid 中刪除該return super().form_valid(form)
行。
這行代碼將從繼承類中調用 form_valid 來保存對象 - 這是在沒有外鍵的情況下創建的額外對象。
相反,您將希望返回某種 http 響應(例如 render_to_response、重定向等)。
添加回答
舉報
0/150
提交
取消