Как импортировать объект другой модели (A) внутрь модели (B) в Django?

Я хочу создать новый объект в модели B при выполнении определенных условий в модели A, я новичок в Django, поэтому я не могу понять, как именно я могу этого добиться.

Например, у меня есть две модели (Product и Product Variant), когда выполняется определенное условие на Product Variant, я хочу вычислить новое значение объекта в Product Model.

Моя модель продукта выглядит следующим образом:

PRODUCT_TYPE = (
('s', 'simple'),
('v', 'varaible')

)

class Products(models.Model):
name = models.CharField(max_length=250,null=True, blank=True,)
slug = models.SlugField(max_length=200, unique=True,null=True)
short_description = HTMLField()
description = HTMLField()
category = models.ForeignKey(Categories, related_name="products",on_delete=models.SET_NULL,null=True,blank=True,)
brand = models.ForeignKey(Brands,on_delete=models.CASCADE, default=None, null=True, blank=True,)
warranty_support = HTMLField()
product_type = models.CharField(choices=PRODUCT_TYPE, default='simple', max_length=50)

А моя модель атрибутов продукта выглядит так:

class ProductVariant(models.Model):
product = models.ForeignKey(Products,on_delete=models.CASCADE)
variant = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE, null = True, default=None)
managed_stock = models.IntegerField(choices=STOCK_MANAGED, default=0)
stock = models.IntegerField(default=None)
stock_threshold = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
sku = models.CharField(max_length= 250, default=None)
sale_price = models.DecimalField(max_digits=10, decimal_places=2)
sale_start_date=models.DateField(auto_now_add=False, auto_now=False, default=None)
sale_end_date=models.DateField(auto_now_add=False, auto_now=False,default=None)

Я пытаюсь создать регулярную_цену и цену_продажи в модели Product, если product_type является переменной и если sale_end_date больше, чем сегодня. Я хочу установить цену из варианта, который имеет самую низкую цену.

Я попробовал сделать вот так на Product Model:

def clean(self):
    if self.product_type == 'varaible' and ProductVariant.objects.filter(product=self, variant_count__gt = 1):
             
        self.min_price = ProductVariant.objects.filter(product=self).Min('price')
        self.max_price = ProductVariant.objects.filter(product=self).Max('price')

но я не могу достичь желаемого, Как я могу это сделать?

После некоторых исследований и анализа я нашел решение моей проблемы, я размещаю решение здесь, чтобы кто-то с похожей проблемой мог получить пользу.

@property
    def get_price(self):
        result = dict()
        variants = ProductVariant.objects.filter(product=self)
        count = variants.count()
        if count > 1:
            min_variant = variants.order_by('price').first()
            max_variant = variants.order_by('-price').first()
            result['min_price'] = min_variant.price
            result['max_price'] = max_variant.price

        elif count == 1:
            variant = variants.first()
            if variant.sale_price:
                result['price'] = variant.price
                result['sale_price'] = variant.sale_price
                sale_variant = variants.order_by('sale_price').first()
                result['lowest_sale_price'] = sale_variant.sale_price
                result['regular_price'] = sale_variant.price
                today = datetime.date.today()
                if variant.sale_start_date <= today and variant.sale_end_date >= today:
                    result['sale_end_date'] = variant.sale_end_date
            else:
                result['price'] = variant.price
Вернуться на верх