简体   繁体   English

django UNIQUE约束失败错误

[英]django UNIQUE constraint failed error

I have fallowing structure of database. 我的数据库结构不好。 I create ProductBidPrice class on view. 我在视图上创建ProductBidPrice类。 Add all column has not have any problem but one column which is out_going_price and income_price . 添加所有列没有任何问题,但其中一列是out_going_priceincome_price When I save the new ProductBidPrice django throw this error 当我保存新的ProductBidPrice django时抛出此错误

"UNIQUE constraint failed: sales_productbidprice.price_income_id" “唯一约束失败:sales_productbidprice.price_income_id”

. I want use more than one to one realtionship. 我想使用多个一对一的代理关系。

I can add and save Django Web Interface. 我可以添加和保存Django Web Interface。 But I can't add in the view. 但是我无法添加视图。

How can I fix this problem ? 我该如何解决这个问题?

Sorry about my English. 对不起,我的英语。 I hope explain my problem. 我希望能解释我的问题。

models.py 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 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})

You have defined this field as a one to one relationship. 您已将该字段定义为一对一关系。

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

So only one ProductBidPrice can have one ProductIncomePriceHistory the error is probably raised because you already have a ProductBidPrice with the ProductIncomePriceHistory.id you are trying to use. 因此,只有一个ProductBidPrice可以具有一个ProductIncomePriceHistory ,可能会引发该错误,因为您已经在尝试使用具有ProductIncomePriceHistory.id的ProductBidPrice。

I believe you want a many to on relationship, if I am interpreting what you are trying to do correctly. 我相信,如果我正在解释您要正确做的事情,那么您希望与您建立许多关系。

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()

use this model as OneToOneField will raise error if same number is tried to be inserted which exist in the database 使用此模型,因为如果尝试插入数据库中存在的相同数字,则OneToOneField将引发错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM