Jakub-Wilk
Jakub-Wilk

Reputation: 49

Django - how to access a ForeignKey parent's attribute?

I'm a newbie in Django, and I don't know how to this.

I have a model 'Seller':

class Seller(models.Model):
    seller_name = models.CharField(max_length=50)
    def __str__(self):
        return self.seller_name

and a model 'Item':

class Item(models.Model):
    seller = models.ForeignKey(Seller, on_delete=models.CASCADE)
    item_name = models.CharField(max_length=100)
    item_category = models.CharField(max_length=100, choices=ALL_CATEGORIES)
    item_price = models.FloatField()
    item_preview = models.ImageField(upload_to='previews/<the seller's name>')
    def __str__(self):
        return self.item_name

connected via ForeignKey to Seller.

In this model, I have an ImageField, and I want it to upload the files to previews/Seller's name directory, but I don't know how to access the Seller's name from Item. Is it possible? Or am I doing something I am not supposed to? Because I couldn't find any similar cases in the internet.

Upvotes: 0

Views: 1521

Answers (1)

a_k_v
a_k_v

Reputation: 1608

You can access Seller name like this.

item = Item.objects.get(<condition>)
item.seller.seller_name

If you are using filter

   items = Item.objects.filter(<condition>)
    items[0].seller.seller_name #You need to provide index in queryset

   or
   for item in items:
      item.seller.seller_name

you can't provide a path like that. You can either use a callable in upload_to or can use the lambda function.

item_preview = models.ImageField(upload_to=lambda instance: 'previews/{0}'.format(instance.seller.seller_name))

If you use upload_to callable

  item_preview = models.ImageField(upload_to=upload_file_handler)
  def upload_file_handler(instance, filename):   
    return 'previews/{0}'.format(instance.seller.seller_name)

Upvotes: 2

Related Questions