我正在使用 Django createview 在拍賣(mài)網(wǎng)站中創(chuàng)建投標(biāo)項(xiàng)目。createview 將創(chuàng)建新對(duì)象,但它會(huì)創(chuàng)建一個(gè)沒(méi)有相應(yīng)外鍵的額外對(duì)象實(shí)例。我正在使用 @staticmethod 來(lái)確定提交的出價(jià)是否確實(shí)是最高出價(jià),然后在相關(guān)列表中創(chuàng)建。如果您能指出我做錯(cuò)了什么,請(qǐng)?zhí)崆爸轮x。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 回答

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