dimanche 13 mai 2018

Django Models: __str__ with Foreign object's name

So I have a Product and ProductImage models. Each Product can have multiple ProductImage models. In the Django admin page, I want the product images to display the name of the product it's related to.

class Product(models.Model):
    name = models.CharField(max_length=150)
    price = models.DecimalField(max_digits=9, decimal_places=2)
    product_count = models.IntegerField(blank=True, default=0)
    description = models.TextField()



class ProductImage(models.Model):
    image_addr = models.FileField(upload_to='products/')
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)

    def __str__(self):
        q = <*name of the product with the product_id*>

If a product image is that of a phone, say iPhone X, the image should display so. Now, the product images column only shows ProductImage objects. How do I solve this? enter image description here




Aucun commentaire:

Enregistrer un commentaire