Donovan Keating
Donovan Keating

Reputation: 1885

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

Upvotes: 1

Views: 1666

Answers (2)

user9754369
user9754369

Reputation:

Ideally you should have a unicode method in each model so that you can view you data in more descriptive way. Your model should like this

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()

    def __unicode__(self):
        return u"{}-{}".format(self.id, self.name)

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

    def __unicode__(self):
        return u"{}".format(self.product_id)

Here i am suggesting unicode instead of str because if product name contains non-ascii character then str will raise error.

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

Try this.

TIP: instead of product_id the field name could be product

if you change the name product_id to product, remember to product_id, in the following

def __str__(self):
    return "%s %s" % (self.product_id.name, self.product_id.id )

Upvotes: 3

Related Questions