英文:
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="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)
and my view function is this
def saleReturn(request):
if not request.user.is_authenticated:
return redirect('login')
elif request.user.userRole != 'admin':
return render(request, 'pages/404.html')
else:
if request.method == "POST":
try:
searchSaleInvoiceId = request.POST.get('searchSaleInvoice')
searchSaleInvoice = SaleInvoice.objects.get(id=searchSaleInvoiceId)
invoiceDateSaleReturn = request.POST.get('invoiceDateSaleReturn')
saleReturnObject = SaleReturn(
user=request.user,
searchSaleInvoice=searchSaleInvoice,
invoiceDateSaleReturn=invoiceDateSaleReturn,
)
saleReturnObject.invoiceDateSaleReturn = date.today()
saleReturnObject.save()
print("saleReturnObject",saleReturnObject)
saleReturnItemNameId = request.POST.get('saleReturnItemName')
saleReturnItem = Egg.objects.get(eggName=saleReturnItemNameId)
print("-----------------1----------------------")
saleReturnItemNameId = saleReturnItem.id
saleReturnItemQuantity = request.POST.getlist('saleReturnItemQuantity')
saleReturnItemUnitPrice = request.POST.getlist('saleReturnItemUnitPrice')
saleReturnItemDiscount = request.POST.getlist('saleReturnItemDiscount')
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 == '':
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("saleReturnItemObject",saleReturnItemObject)
# Adding Item in Egg
Egg.objects.filter(id=item_name.saleInvoiceItemName.id).update(
eggStockQuantity=F('eggStockQuantity') + 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, 'Record Saved Successfully.')
return redirect('saleReturn')
except Exception as e:
messages.error(request, f'Some Error Occurred While Saving Data: {str(e)}')
saleReturnData = SaleReturn.objects.all()
results = SaleInvoice.objects.all()
return render(request, 'pages/addSaleReturn.html', {'saleReturnData': saleReturnData, 'results': results})
and my html is this
<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;"/>
<!-- <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>
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=<INSTANCE ID>)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论