如何避免创建重复对象

2024-04-19 09:45:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

另一个有外传钥匙的模型

^{pr2}$

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

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比较陌生,编程一般来说我刚开始,所以一个轻推,一个推,指向正确方向的人会很感激我会继续在这个网站上搜索类似的东西我相信有人可能偶然发现了类似的东西。谢谢你的建议


Tags: oftheinstancetextnamebranchtruemodels
1条回答
网友
1楼 · 发布于 2024-04-19 09:45:13

为了完成您想要的,您可以在第一个过程中添加一个布尔检查。在

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

我添加了ischureate作为函数的参数、check和return。ischureated可以设置为此函数范围之外的变量,然后在每次调用该函数时传递给该函数。在

所以

^{pr2}$

相关问题 更多 >