How do I automatically inherit a foreignkey model's field in django rest?

Viewed 152

enter image description hereModels.py, From django admin what I do is I can add a product to Featured but the problem is when I select a product in admin to make featured I want to automatically inherit that product's image url which was uploaded when that product was created.

class Product(models.Model):
    seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
    title = models.CharField(max_length=120, primary_key=True)

    image = models.FileField()
    def __str__(self):
        return self.title


class FeaturedProduct(models.Model):
    db_identification = models.CharField(max_length=120)
    featured = models.ForeignKey(Product, on_delete=models.CASCADE)

    photograph = How do I inherit it automatically from foreignkey product selected?
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.db_identification
2 Answers

Actually, it is probably not a good idea to duplicate the image. Indeed, a database is designed to avoid data duplication. Anyway in your code, if you want the Product image for a given FeaturedProduct you can use :

featured_product = FeaturedProduct.object.get(...)
image = feature_product.product.image

This way, you have no duplication. (Easier in case of image changing for example !).

EDIT : If you want to easily access from FeaturedProduct, you can add a util method :

class FeaturedProduct(models.Model):
    db_identification = models.CharField(max_length=120)
    featured = models.ForeignKey(Product, on_delete=models.CASCADE)

    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.db_identification

    @property
    def photograph(self):
       return self.product.image

You can override the save function of the FeaturedProduct

class FeaturedProduct(models.Model):
    db_identification = models.CharField(max_length=120)
    featured = models.ForeignKey(Product, on_delete=models.CASCADE)

    photograph = models.FileField(blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.db_identification

    def save(self, *args, **kwargs):
        self.photograph = self.featured.image
        super(FeaturedProduct, self).save(*args, **kwargs)
Related