These are chat archives for django/django

19th
Sep 2018
Garrus Napp
@GarrusNapp
Sep 19 2018 13:12
hey guys, i've got a product model with several price as foreign keys. I want to display a bunch of products and their prices in template, how should I go about it?
Shashank Parekh
@sp1rs
Sep 19 2018 13:13
@GarrusNapp Paste the model code.
Garrus Napp
@GarrusNapp
Sep 19 2018 13:14
class Product(models.Model):
    name = models.CharField(max_length=500, blank=False)
    description = models.CharField(max_length=1000)
    image = models.ImageField(upload_to='uploads/%Y/%m/%d/')
    featured = models.BooleanField(default=False)
    category = models.ManyToManyField(Category, related_name="product")
    @property
    def image_url(self):
        if self.image and hasattr(self.image, 'url'):
            return self.image.url

    def __str__(self):
        return self.name


class Price(models.Model):
    shop = models.CharField(
        max_length=30,
        blank=False
    )
    amount = models.DecimalField(max_digits=6, decimal_places=2)
    price = models.ForeignKey(Product, on_delete=models.CASCADE, blank=False, related_name="prices")

    def __str__(self):
        return "Price of " + str(self.price)