Skip to main content
 首页 » 编程设计

python之如何避免重复创建对象

2024年12月31日9lori

我现在有重复问题我不知道前进的方向需要帮助 我有这个模型分支与股票有反向关系

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

在我的股票应用程序中,我有一个信号,如果它不存在,我想为另一个分支创建新的股票对象。

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 比较陌生,一般的编程我刚刚开始所以在正确的方向上轻推,插入,指针将非常感激我将继续在这个网站上搜索类似的东西我相信有人可能已经偶然发现了类似的东西。致谢

请您参考如下方法:

要完成您想要的,您可以在第一遍中添加 bool 检查。

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_created 可以设置为此函数范围之外的变量,然后在每次调用时传递给该函数。

所以

out_scope_created = False 
out_scope_created = update_stock_on_waybill(sender,instance,out_scope_created)