A
A
Alexander2021-02-14 11:15:02
Django
Alexander, 2021-02-14 11:15:02

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)


I need to get the slug attribute from the Hotel model in order to pass it to the get_upload_path function, which renames the file and generates the path to upload it. With other models where the slug field is created like this: slug = models.SlugField(max_length=150, unique=True) - the function works.

i tried like this:

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".


in the second case, the function seems to work, but it is not passed the value of the slug field, but some of its "internals" in the string representation, the length of which is too large.

Tell me, please, where to dig? Maybe this field needs to be received through a class method?

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-02-14
@Quanttor

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 question

Ask a Question

731 491 924 answers to any question