K
K
kirillinyakin2020-06-22 00:08:40
Python
kirillinyakin, 2020-06-22 00:08:40

How to get a foreign key attribute that in turn refers to another foreign key?

Hello, this is the question, let's say I have the following model:

class Gallery(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=f'products/', blank=True)

class Product(models.Model):
    sub_category = models.ForeignKey(SubCategory, related_name='products', on_delete=models.CASCADE)

class SubCategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)

I want the image to be saved in the path "category_name/subcategory_name", so this is how you can get the category name, so the way I thought does not work:
product.sub_category.category.name

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Tikhonov, 2020-06-22
@kirillinyakin

upload_to can be a function, the telepathic third dot blinks that way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question