Django: метод модели из запроса другого - PullRequest
1 голос
/ 10 апреля 2019

У меня есть модель CartItem, которая имеет ForeignKey для Product модели.

Поскольку из Product модели я получаю description, image и т. Д.

Однако я хочу иметь метод с именем sub_total, который возвращает целое число.Я использую это, чтобы вычислить сумму, которую нужно заплатить за это CartItem.

Этот метод sub_total запрашивает другую модель costo_de_los_productos, используя некоторые свойства CartItem.как: self.product.category.name, self.product.name, self.size, self.quantity.

Мне нужно вернуть Integer из метода sub_total.

Однако что-тоНе правильно со мной запрос, если я прокомментирую и вернусь 0, он работает, но общее количество равно 0.

def sub_total(self):    
  product_price = costo_de_los_productos.objects.filter(category=self.product.category.name,    
  product = self.product.name,
  size=self.size,
  quantity=self.quantity).values_list("price", flat=True)

Что может быть не так?

class CartItem(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    size = models.CharField(max_length=20, choices=TAMANIOS)
    quantity = models.CharField(max_length=20, choices=CANTIDADES)
    file = models.FileField(upload_to='files', blank=True, null=True)
    comment = models.CharField(max_length=100, blank=True, null=True, default='')
    uploaded_at = models.DateTimeField(auto_now_add=True)
    step_two_complete = models.BooleanField(default=False)

    # def __str__(self):
    #     return str(self.id) + " - " + str(self.size) + " por " + str(self.quantity)

    def sub_total(self):
        product_price = costo_de_los_productos.objects.filter(category = self.product.category.name,
                                         product = self.product.name,
                                         size=self.size,
                                         quantity=self.quantity).values_list("price", flat=True)
        # print(type(product_price))
        return product_price

costo_de_los_productos модель:

class costo_de_los_productos(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    price = models.IntegerField(default=30)
    size = models.CharField(max_length=20, choices=TAMANIOS)
    quantity = models.CharField(max_length=20, choices=CANTIDADES)

модель продукта:

class Product(models.Model):
    name = models.CharField(max_length=250, unique=False)
    slug = models.SlugField(max_length=250, unique=False)
    description = models.TextField(blank=True)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    image = models.ImageField(upload_to='product', blank=True, null=True)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'product'
        verbose_name_plural = 'products'

    def get_url(self):
            return reverse('shop:ProdDetail', args=[self.category.slug, self.slug])

    def __str__(self):
        return '{}'.format(self.name)

модель категории:

class Category(models.Model):
    name = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True, null=True)
    image = models.ImageField(upload_to='category', blank=True, null=True)
    video = EmbedVideoField(null=True, blank=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def get_url(self):
        return reverse('shop:allCat', args=[self.slug])

    def __str__(self):
        return '{}'.format(self.name)

Изображение "costo_de_los_productos" из панели администратора:

enter image description here

ОБНОВЛЕНИЕ 1

Невозможно напечатать что-либо после запроса product_price.

def sub_total(self):
    print("Enters Subtotal")
    print(self.product.category.name)
    print(self.product.name)
    print(self.size)
    print(self.quantity)
    product_price = costo_de_los_productos.objects.filter(category=self.product.category.name,
                                                          product=self.product.name,
                                                          size=self.size,
                                                          quantity=self.quantity).values_list("price", flat=True)[0]

    print("Line after product_price query")
    print(type(product_price))

    return product_price

Жесткое кодирование значений невозвращает ожидаемое целое число:

def sub_total(self):
    print("Enters Subtotal")
    print(self.product.category.name)
    print(self.product.name)
    print(self.size)
    print(self.quantity)
    product_price = costo_de_los_productos.objects.filter(category="Stickers",
                                                          product="Stickers transparentes",
                                                          size="5cm x 5cm",
                                                          quantity=300).values_list("price", flat=True)[0]

    print("Line after product_price query")
    print(type(product_price))

    return product_price

выводит результаты:

Enters Subtotal
Stickers
Stickers transparentes
5cm x 5cm
300
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...