在Django中未通过外键关系获取特定对象。

huangapple go评论73阅读模式
英文:

Not getting specific object using foreign key relationship in django

问题

我遇到了一个问题,我正在尝试通过外键关系获取一个蛋的物品对象,但它一次又一次地显示了这个错误:

保存数据时发生错误:找不到匹配的蛋。

我的模型如下:

class SaleReturnItem(models.Model):
    salereturn = models.ForeignKey(
        SaleReturn,
        on_delete=models.CASCADE, related_name="salereturnitem"
    )
    saleReturnItemName=models.ForeignKey(Egg, on_delete=models.CASCADE, related_name='salereturnitemegg',null=True)
    saleReturnItemQuantity=models.CharField(max_length=15,null=True)
    saleReturnItemUnitPrice=models.CharField(max_length=15,null=True)
    saleReturnItemTotalAmount=models.CharField(max_length=15,null=True)
    saleReturnItemDiscount=models.CharField(max_length=15,null=True)
    saleReturnItemDiscountPrice=models.CharField(max_length=15,null=True)

class Egg(models.Model):
    user = models.ForeignKey(
        get_user_model(),
        on_delete=models.CASCADE,default=1
    )
    eggName = models.TextField(null=True)
    eggInSection = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='eggsection',default=1)
    eggSalePrice = models.CharField(max_length=15,default=False)
    eggPurchasePrice = models.CharField(max_length=15,default=False)
    eggStockLimit = models.IntegerField(default=False)
    eggStockQuantity = models.IntegerField(default=False)
    eggInCategory = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='eggcategory',default=1)
    eggExpiryDate = models.DateField(blank=True, null=True)
    eggGst = models.DecimalField(max_digits=5, decimal_places=2,default=False)

我的视图函数如下:

def saleReturn(request):
    # ...
    if request.method == "POST":
        try:
            # ...
            saleReturnItemNameId = request.POST.get('saleReturnItemName')
            saleReturnItem = Egg.objects.get(eggName=saleReturnItemNameId)
            # ...

我的HTML如下:

<tbody class="table-border-bottom-0" id="item-table-body">
    <tr class="item-row">
        <td>
            <h6 class="item-number"/>
        </td>
        <td>
            <input type="text" id="saleReturnItemNameId" name="saleReturnItemName"
                class="form-control item-name" placeholder="Search"
                style="height: 40px; width: 150px;"/>
        </td>
        <td>
            <input for="saleReturnItemQuantity" type="number" class="form-control item-quantity"
                id="saleReturnItemQuantityId" name="saleReturnItemQuantity"
                style="height: 40px; width: 150px;"/>
        </td>
        <td>
            <input type="string" class="form-control item-price" id="saleReturnItemUnitPriceId"
                name="saleReturnItemUnitPrice"/>
        </td>
        <td>
            <input type="number" class="form-control item-total-amount"
                id="saleReturnItemTotalAmountId" name="saleReturnItemTotalAmount"/>
        </td>
        <td>
            <input type="number" class="form-control item-discount" id="saleReturnItemDiscountId"
                name="saleReturnItemDiscount"/>
        </td>
        <td>
            <input type="number" class="form-control item-discounted-amount"
                id="saleReturnItemDiscountPriceId" name="saleReturnItemDiscountPrice"/>
        </td>
    </tr>
</tbody>

主要的概念是我正在获取SaleReturn项目,这些项目是从Egg模型中检索出来的,但我努力尝试了很多次,但我无法获取蛋对象。

英文:

I am facing an issue where I'm trying to get an Egg item object by using foreign key relationship but it again and again show me this error

Some Error Occurred While Saving Data: Egg matching query does not exist.

My models are:

class SaleReturnItem(models.Model):
salereturn = models.ForeignKey(
    SaleReturn,
    on_delete=models.CASCADE,related_name=&quot;salereturnitem&quot;
)
saleReturnItemName=models.ForeignKey(Egg, on_delete=models.CASCADE, related_name=&#39;salereturnitemegg&#39;,null=True)
saleReturnItemQuantity=models.CharField(max_length=15,null=True)
saleReturnItemUnitPrice=models.CharField(max_length=15,null=True)
saleReturnItemTotalAmount=models.CharField(max_length=15,null=True)
saleReturnItemDiscount=models.CharField(max_length=15,null=True)
saleReturnItemDiscountPrice=models.CharField(max_length=15,null=True)

class Egg(models.Model):
user = models.ForeignKey(
    get_user_model(),
    on_delete=models.CASCADE,default=1
)
eggName = models.TextField(null=True)
eggInSection = models.ForeignKey(Section, on_delete=models.CASCADE, related_name=&#39;eggsection&#39;,default=1)
eggSalePrice = models.CharField(max_length=15,default=False)
eggPurchasePrice = models.CharField(max_length=15,default=False)
eggStockLimit = models.IntegerField(default=False)
eggStockQuantity = models.IntegerField(default=False)
eggInCategory = models.ForeignKey(Category, on_delete=models.CASCADE, related_name=&#39;eggcategory&#39;,default=1)
eggExpiryDate = models.DateField(blank=True, null=True)
eggGst = models.DecimalField(max_digits=5, decimal_places=2,default=False)

and my view function is this

def saleReturn(request):
if not request.user.is_authenticated:
    return redirect(&#39;login&#39;)
elif request.user.userRole != &#39;admin&#39;:
    return render(request, &#39;pages/404.html&#39;)
else:
    if request.method == &quot;POST&quot;:
        try:
            searchSaleInvoiceId = request.POST.get(&#39;searchSaleInvoice&#39;)
            searchSaleInvoice = SaleInvoice.objects.get(id=searchSaleInvoiceId)
            invoiceDateSaleReturn = request.POST.get(&#39;invoiceDateSaleReturn&#39;)

            saleReturnObject = SaleReturn(
                user=request.user,
                searchSaleInvoice=searchSaleInvoice,
                invoiceDateSaleReturn=invoiceDateSaleReturn,
            )
            saleReturnObject.invoiceDateSaleReturn = date.today()
            saleReturnObject.save()
            print(&quot;saleReturnObject&quot;,saleReturnObject)

            saleReturnItemNameId = request.POST.get(&#39;saleReturnItemName&#39;)
            saleReturnItem = Egg.objects.get(eggName=saleReturnItemNameId)
            print(&quot;-----------------1----------------------&quot;)
           
            saleReturnItemNameId = saleReturnItem.id
           
            

            saleReturnItemQuantity = request.POST.getlist(&#39;saleReturnItemQuantity&#39;)
            saleReturnItemUnitPrice = request.POST.getlist(&#39;saleReturnItemUnitPrice&#39;)
            saleReturnItemDiscount = request.POST.getlist(&#39;saleReturnItemDiscount&#39;)

            totalSaleAmountSaleReturn = 0.0
            saleInvoiceAmountSaleReturn = 0.0
            saleInvoiceDiscountSaleReturn = 0.0

            for saleReturnItemNameId,quantity, price, discount,  in zip(saleReturnItemNameIds,
                saleReturnItemQuantity, saleReturnItemUnitPrice, saleReturnItemDiscount
            ):
                saleReturnItemName = next(item for item in saleReturnItemNames if item.id == int(saleReturnItemNameId))
                total_amount = int(quantity) * float(price)
                if discount == &#39;&#39;:
                    discount = 0.0
                else:
                    discount = float(discount)
                discounted_amount = total_amount - discount

                # item_name = saleReturnItemNames.get(id=item_id)

                saleReturnItemObject = SaleReturnItem(
                    salereturn=saleReturnObject,
                    saleReturnItemName_id=saleReturnItemNameId,
                    saleReturnItemQuantity=quantity,
                    saleReturnItemUnitPrice=price,
                    saleReturnItemTotalAmount=str(total_amount),
                    saleReturnItemDiscount=discount,
                    saleReturnItemDiscountPrice=str(discounted_amount)
                )
                saleReturnItemObject.save()
                print(&quot;saleReturnItemObject&quot;,saleReturnItemObject)

                # Adding Item in Egg
                Egg.objects.filter(id=item_name.saleInvoiceItemName.id).update(
                    eggStockQuantity=F(&#39;eggStockQuantity&#39;) + int(quantity)
                )

                totalSaleAmountSaleReturn += total_amount
                saleInvoiceAmountSaleReturn += discounted_amount
                saleInvoiceDiscountSaleReturn += discount

            saleReturnObject.totalSaleAmountSaleReturn = float(totalSaleAmountSaleReturn)
            saleReturnObject.saleInvoiceAmountSaleReturn = float(saleInvoiceAmountSaleReturn)
            saleReturnObject.saleInvoiceDiscountSaleReturn = float(saleInvoiceDiscountSaleReturn)
            saleReturnObject.save()

            messages.success(request, &#39;Record Saved Successfully.&#39;)
            return redirect(&#39;saleReturn&#39;)
        except Exception as e:
            messages.error(request, f&#39;Some Error Occurred While Saving Data: {str(e)}&#39;)

    saleReturnData = SaleReturn.objects.all()
    results = SaleInvoice.objects.all()
   

    return render(request, &#39;pages/addSaleReturn.html&#39;, {&#39;saleReturnData&#39;: saleReturnData, &#39;results&#39;: results})

and my html is this

&lt;tbody class=&quot;table-border-bottom-0&quot; id=&quot;item-table-body&quot;&gt;
    &lt;tr class=&quot;item-row&quot;&gt;
        &lt;td&gt;
            &lt;h6 class=&quot;item-number&quot;/&gt;
        &lt;/td&gt;
        &lt;td&gt;
            &lt;input type=&quot;text&quot; id=&quot;saleReturnItemNameId&quot; name=&quot;saleReturnItemName&quot;
                class=&quot;form-control item-name&quot; placeholder=&quot;Search&quot;
                style=&quot;height: 40px; width: 150px;&quot;/&gt;
            &lt;!-- &lt;input type=&quot;text&quot; id=&quot;saleReturnItemNameId&quot; name=&quot;saleReturnItemName&quot; class=&quot;form-control item-name&quot; placeholder=&quot;Search&quot; style=&quot;height: 40px; width: 150px;&quot;/&gt;                                                                    --&gt;
        &lt;/td&gt;
        &lt;td&gt;
            &lt;input for=&quot;saleReturnItemQuantity&quot; type=&quot;number&quot; class=&quot;form-control item-quantity&quot;
                id=&quot;saleReturnItemQuantityId&quot; name=&quot;saleReturnItemQuantity&quot;
                style=&quot;height: 40px; width: 150px;&quot;/&gt;
        &lt;/td&gt;
        &lt;td&gt;
            &lt;input type=&quot;string&quot; class=&quot;form-control item-price&quot; id=&quot;saleReturnItemUnitPriceId&quot;
                name=&quot;saleReturnItemUnitPrice&quot;/&gt;

        &lt;/td&gt;
        &lt;td&gt;
            &lt;input type=&quot;number&quot; class=&quot;form-control item-total-amount&quot;
                id=&quot;saleReturnItemTotalAmountId&quot; name=&quot;saleReturnItemTotalAmount&quot;/&gt;

        &lt;/td&gt;

        &lt;td&gt;
            &lt;input type=&quot;number&quot; class=&quot;form-control item-discount&quot; id=&quot;saleReturnItemDiscountId&quot;
                name=&quot;saleReturnItemDiscount&quot;/&gt;

        &lt;/td&gt;
        &lt;td&gt;
            &lt;input type=&quot;number&quot; class=&quot;form-control item-discounted-amount&quot;
                id=&quot;saleReturnItemDiscountPriceId&quot; name=&quot;saleReturnItemDiscountPrice&quot;/&gt;

        &lt;/td&gt;
    &lt;/tr&gt;
&lt;/tbody&gt;

The main concept is I'm getting SaleReturn items and that items are retrieved from Egg model but I tried hard and I am not getting the egg object.

答案1

得分: 1

在 eggName 方面可能存在拼写错误。

请确保您在“get”查询中传递的值拼写完全相同

或者如果您收到的值与数据库中保存的值不同,您可以稍微修改查询
例如,
如果在数据库中保存了'Abc',而您在get查询中传递了值“abc”,它将导致错误。

要解决此问题,您可以修改查询

Egg.objects.get(eggName__iexact=saleReturnItemNameId)

尽管不推荐在 get 查询中使用字符串匹配。您应该发送实例的 ID 来执行 get 查询。

类似这样:

Egg.objects.get(id=<实例ID>)
英文:

There must be some spelling error in case of eggName.

Make sure the value that you are passing in the "get" query has exact same spelling

Or you can modify your query a little bit if you are receiving value in lower case or different from what is saved in the DB
For eg,
If 'Abc' is saved in DB and you are passing the value "abc" in the get query, it will give you error.

To resolve this, you can modify your query

Egg.objects.get(eggName__iexact=saleReturnItemNameId)

Although it is not recommended to use string matching in case of get query. You should send the id of the instance to make a get query.

Something like this:

Egg.objects.get(id=&lt;INSTANCE ID&gt;)

huangapple
  • 本文由 发表于 2023年6月9日 02:53:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76434905.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定