Python 如何避免重复对象创建
我现在有复制问题我不知道前进的方向需要帮助 我有一个与股票相反的模型分行Python 如何避免重复对象创建,python,django,Python,Django,我现在有复制问题我不知道前进的方向需要帮助 我有一个与股票相反的模型分行 class Branch(models.Model): name = models.CharField( 'Branch', unique=True, max_length=10, validators=[MinLengthValidator(5)]) location = models.TextField(max_length=650,
class Branch(models.Model):
name = models.CharField(
'Branch',
unique=True,
max_length=10,
validators=[MinLengthValidator(5)])
location = models.TextField(max_length=650,
blank=True,
help_text='location of the linsan branch')
class Meta:
verbose_name_plural = 'Branch'
def __str__(self):
return self.name
class Stock(models.Model):
branch = models.ForeignKey(
Branch,
related_name = 'branch',
help_text='Enter the name of the branch',
on_delete=models.CASCADE,
blank=False,
null=False
)
manufacturers_name = models.CharField(
max_length=50,
blank=True)
description = models.CharField(
max_length=50,
help_text='Enter the name of the product here',
unique=True
)
model_number = models.CharField(
max_length=25,
blank=True,
null=True,
help_text='Enter the model number of the item if any')
color = models.CharField(
max_length=20,
default='black',
blank=True,
null=True,)
quantity = models.PositiveIntegerField(
validators=[validate],
verbose_name='Quantity In stock')
retail_price = MoneyField(
max_digits=14,
decimal_places=2,
default_currency='NGN',
blank=False,
verbose_name="Retail Price")
customer_price = MoneyField(
max_digits=14,
decimal_places=2,
default_currency='NGN',
blank=False)
added = models.DateTimeField(
auto_now_add=True,
help_text='The date the product was added')
image = models.ImageField(
blank=True,
null=True,
upload_to='uploads/%Y/%m/%d/',
help_text='Upload the image of the product if any')
history = HistoricalRecords()
class Meta:
ordering = ['description']
def __str__(self):
return self.description
还有另一款有外国股票密钥的车型
class WaybillItem(models.Model):
waybill = models.ForeignKey(Waybill,
on_delete=models.CASCADE,
related_name='waybill_item')
product = models.ForeignKey(
'stock.Stock',
on_delete=models.CASCADE,
blank=False,
null=False)
quantity = models.PositiveIntegerField(validators=[validate, MinValueValidator(1)])
在我的stock应用程序中,我有一个信号,如果另一个分支不存在,我想创建一个新的stock对象
def update_stock_on_waybill(sender, instance, **kwargs):
transferred_to = instance.waybill.transferred_to.branch.all()
product = instance.product
if product in transferred_to:
print("it is!")
pass
else:
print("it isn't")
Stock.objects.create(
branch=instance.product.branch,
description=instance.product.description,
model_number=instance.product.model_number,
color=instance.product.color,
quantity=instance.quantity,
retail_price=instance.product.retail_price,
customer_price=instance.product.customer_price
)
product.save()
pre_save.connect(update_stock_on_waybill, sender=WaybillItem)
但每次我保存一个不存在的新运单(**我排除了模型)时,它会创建一个新的对象,这很好,但如果对象确实存在,则同样适用,我对python、django比较陌生,一般来说,编程我刚开始,所以轻推,指向正确方向的人会非常感激,我会继续在这个网站上搜索类似的东西,我相信有人可能偶然发现了类似的东西。感谢adv要完成您想要的任务,您可以在第一个过程中添加布尔检查
def update_stock_on_waybill(sender, instance,is_create, **kwargs):
transferred_to = instance.waybill.transferred_to.branch.all()
product = instance.product
if is_create:
print("it is!")
pass
else:
print("it isn't")
Stock.objects.create(
branch=instance.product.branch,
description=instance.product.description,
model_number=instance.product.model_number,
color=instance.product.color,
quantity=instance.quantity,
retail_price=instance.product.retail_price,
customer_price=instance.product.customer_price
)
is_create = True
product.save()
pre_save.connect(update_stock_on_waybill, sender=WaybillItem)
return is_create
我添加了is_create作为函数的参数、检查和返回。可以将创建的is_设置为此函数范围之外的变量,然后在每次调用时传递给该函数
所以
我对类似情况的处理略有不同。 我在对象创建中添加了一组现有项(对象的标识符)。 然后,如果新对象已经存在,我将使类中的初始化失败
class firstone:
def __init__(self,name:str,chk:set):
if name in chk:
raise ValueError
self.name = name
chk.add(name)
def get_name(self) -> str:
return self.name
创建一个集合并实例化第一个对象
nmset=set()
a=firstone("a",nmset)
a.get_name()
返回“a”
nmset
返回仅包含“a”的集
b=firstone("a",nmset)
抛出可以以任何方式处理的ValueError
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-312c2fbf49eb> in <module>
----> 1 b=firstone("a",nmset)
<ipython-input-13-660b12b68b44> in __init__(self, name, chk)
2 def __init__(self,name:str,chk:set):
3 if name in chk:
----> 4 raise ValueError
5 self.name = name
6 chk.add(name)
ValueError:
---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在里面
---->1 b=第一个(“a”,nmset)
in_uuuinit_uuu(self,name,chk)
2定义初始化(self,名称:str,chk:set):
3如果名称在chk中:
---->4升值错误
5 self.name=名称
6.添加(名称)
值错误:
缺点是必须通过集合,但我发现这是一种更容易的方法,当对象可以从很多地方实例化时…我是否正确理解您只想创建一次此对象,只有一次?是的,这就是我想为某个特定分支做的事情。你可以使用
get\u或\u create
而不是create
,但是为什么所有这些冗余数据而不是从库存到产品的外键呢?为什么不在第一次通过时添加类似is\u create=True的布尔值,如果对象停止复制,我打算做什么?例如:如果在另一个分支中已经有对象,而不是创建新的对象,我想添加到数量中,那么让我检查一下,然后回来哦,我的错,我已经解决了。不过我还是坚持你的答案。
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-17-312c2fbf49eb> in <module>
----> 1 b=firstone("a",nmset)
<ipython-input-13-660b12b68b44> in __init__(self, name, chk)
2 def __init__(self,name:str,chk:set):
3 if name in chk:
----> 4 raise ValueError
5 self.name = name
6 chk.add(name)
ValueError: