Answer the question
In order to leave comments, you need to log in
How to get model attribute value by ForeignKey?
Good afternoon!
there are two models:
class Hotel(models.Model):
name = models.CharField('Наименование отеля', max_length=150)
#я убрал здесь некоторые поля
slug = models.SlugField(max_length=150, unique=True)
def __str__(self):
return self.name
class HotelImage(models.Model):
hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, verbose_name='Отель')
#slug = ... (здесь я хочу получить slug из класса Hotel)
image = models.ImageField(upload_to=get_upload_path)
slug = Hotel.slug
#Ошибка: HotelImage has no field named 'slug'
slug = str(Hotel.slug)
#Ошибка: Storage can not find an available filename for "img_hotels\<django.db.models.query_utils.DeferredAttribute object at 0x000000A1639F5310>\django.db.models.query_utils.DeferredAttribute_object_at_0x000000A1639F5310-3d6ae_VIhJkIQ.jpg". Please make sure that the corresponding file field allows sufficient "max_length".
Answer the question
In order to leave comments, you need to log in
HotelImage has no field named 'slug'you are clearly written that you are working with the HotelImage object, where is this cash desk slug? So you need Hotel.hotel.slug. Well, calling a class instance the name of an existing class is a very bad idea, well, read about pep8.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question