django UNIQUE 约束失败错误

django UNIQUE constraint failed error

我有以下数据库结构。我在视图上创建 ProductBidPrice class。添加所有列没有任何问题,但一列是 out_going_priceincome_price。当我保存新的 ProductBidPrice django 抛出这个错误

"UNIQUE constraint failed: sales_productbidprice.price_income_id"

。我想使用多个一对一关系。

我可以添加和保存 Django Web 界面。但是我无法在视图中添加。

我该如何解决这个问题?

对不起我的英语。我希望解释我的问题。

models.py

    class ProductPriceHistory(BaseModel):
        currency = models.ForeignKey(PriceCurrency)
        price = models.FloatField()
        date = models.DateField()

        class Meta:
            abstract = True


    class ProductIncomePriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_income")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)


    class ProductOutgoingPriceHistory(ProductPriceHistory):
        product = models.ForeignKey(Product, related_name="prices_outgoing")

        def __str__(self):
            return "%s %s of %s" % (self.price, self.currency.name, self.product.name)


class AbstractBidDirectSales(BaseModel):
    name = models.CharField(max_length=45)
    sales_date = models.DateField()
    customer = models.ForeignKey(Customer)

    class Meta:
        abstract = True


    class Bid(AbstractBidDirectSales):
        products = models.ManyToManyField(Product, related_name="bids", through="ProductBidPrice")

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)


    class DirectSale(AbstractBidDirectSales):
        product = models.ManyToManyField(Product, related_name="directSales",  through="ProductDirectSalesPrice")

        class Meta:
            verbose_name_plural = "DirectSales"

        def __str__(self):
            return "%s of %s" % (self.name, self.customer.name)


    class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)


    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.OneToOneField(ProductIncomePriceHistory)
        price_outgoing = models.OneToOneField(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)

views.py

@login_required(login_url="/login/")
def add_bid(request):
    if request.method == "POST":
        new_bid = Bid();
        new_bid.name = request.POST["name"];
        new_bid.sales_date = request.POST["date"];
        new_bid.customer_id = request.POST["customerSelection"];
        new_bid.save();
        price = request.POST;
        items = [];
        pieces = [];
        ubb_code = [];
        for q in price:
            if q.startswith("item"):
                items.append(q);
            if q.startswith("piece"):
                pieces.append(q);
            if q.startswith("productSelection"):
                ubb_code.append(q);
        items = sorted(items);
        pieces = sorted(pieces);
        ubb_code = sorted(ubb_code);

        for i in range(len(items)):
            new_bid_product = ProductBidPrice();
            new_bid_product.bid = new_bid;
            new_bid_product.product_id = request.POST[ubb_code[i]];
            new_bid_product.item_number = request.POST[items[i]];
            new_bid_product.piece = request.POST[pieces[i]];
            income_price = ProductIncomePriceHistory.objects.filter(product_id= request.POST[ubb_code[i]]);
            outgoing_price = ProductOutgoingPriceHistory.objects.filter(product_id=request.POST[ubb_code[i]]);
            new_bid_product.price_income_id = income_price[0].id;
            new_bid_product.price_outgoing_id = outgoing_price[0].id;
            new_bid_product.save();

    customers = Customer.objects.all();
    products = Product.objects.all();
    return render(request, "addBid.html", {"customers": customers, "products":products})
class ProductDirectSalesPrice(BaseModel):
        product = models.ForeignKey(Product)
        directSales = models.ForeignKey(DirectSale)
        price_income = models.ForeignKey(ProductIncomePriceHistory)
        price_outgoing = models.ForeignKey(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

        def __str__(self):
            return "%s of %s %s" % (self.product, self.bid.name, self.piece)


    class ProductBidPrice(BaseModel):
        product = models.ForeignKey(Product)
        bid = models.ForeignKey(Bid)
        price_income = models.ForeignKey(ProductIncomePriceHistory)
        price_outgoing = models.ForeignKey(ProductOutgoingPriceHistory)
        item_number = models.IntegerField()
        piece = models.IntegerField()

使用此模型,因为如果尝试插入数据库中存在的相同数字,OneToOneField 将引发错误

您已将此字段定义为一对一关系。

   class ProductBidPrice(BaseModel):
    product = models.ForeignKey(Product)
    bid = models.ForeignKey(Bid)
    price_income = models.OneToOneField(ProductIncomePriceHistory)

所以只有一个 ProductBidPrice 可以有一个 ProductIncomePriceHistory 可能会出现错误,因为您已经有一个 ProductBidPrice 与您正在尝试使用的 ProductIncomePriceHistory.id。

我相信你想要一对多的关系,如果我正确地解释了你正在尝试做的事情。