如何获得所选的外键的值?

发布于 2025-01-21 05:24:26 字数 668 浏览 2 评论 0原文

模型:

class Item(models.Model):
   name = [...] # unique
   quantity = [..integer_field..]

class Sales(models.Model):
   sold_to = [...]
   sold_item = foreign key to Item
   sold_quantity = [..integer field..]

我想确保,如果所选项目的数量为5,并且您将6或更多传递给sold_quantity,请抛出验证>验证错误 “您只有X库存,想出售Y”。 我试图覆盖保存方法,但是我尝试这样做,但它没有任何改变。当我尝试访问self.sold_item时,它将返回所选项目的名称。

当我尝试执行item.objects.get(name = self.sold_item)时,无论我做什么,它都会返回项目的名称,我无法访问其他字段(称为数量)。

浓度: item.Objects.get(name = self.sold_item)返回项目名称。 使用相同但过滤而不是get返回一个QuerySet,其中包含<项目:项目名称>而且我无法访问其他字段。

Models:

class Item(models.Model):
   name = [...] # unique
   quantity = [..integer_field..]

class Sales(models.Model):
   sold_to = [...]
   sold_item = foreign key to Item
   sold_quantity = [..integer field..]

I want to make sure that if the selected Item has the quantity of 5, and you pass 6 or more to the sold_quantity, throw a validation error saying "You have only X in stock and wanted to sell Y".
I tried to override the save method, but however I try to do so, it changes nothing. When I try to access self.sold_item, it returns the name of the selected item.

When I try to do item.objects.get(name=self.sold_item), whatever I do it returns just the name of the item and I can't access other fields (known as Quantity).

Conc:
Item.objects.get(name=self.sold_item) returns the name of the item.
using the same but Filter instead of Get returns a queryset, which contains <Item: the items name> and I can't access other fields of it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

咋地 2025-01-28 05:24:27

根据问题的评论,这是答案

您是否尝试过此self.sold_item.quantity?您只需检查self.sold_item.quantity&lt; self.sold_quantity:提高....

Per a comment on the question, this is the answer

have you tried this self.sold_item.quantity ? you can just check if self.sold_item.quantity < self.sold_quantity: raise ....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文