S
S
shvets22019-07-01 13:21:27
Django
shvets2, 2019-07-01 13:21:27

How to specify field in Django model for ForeignKey?

Hello. There are models Restaurant (restaurant) and RestaurantKitchen (types of cuisine). The Restaurant model has a kitchen field that references the RestaurantKitchen model using a ForeignKey. But when I select data from the database using the Restaurant model, for some reason numbers are indicated in the kitchen field, instead of cuisine (European, Italian, etc.). The code for both models is shown below.

class Restaurant(models.Model):
    is_open = models.BooleanField(default=True, verbose_name='Открыто')
    title = models.CharField(max_length=120, db_index=True, verbose_name='Название')
    slug = models.SlugField(max_length=50, unique=True, help_text=('Используется для создания ЧПУ. '
                                                                   'Можно использовать только маленькие английские '
                                                                   'буквы, цифры и дефис'),
                            verbose_name='ID для ЧПУ')
    description = models.TextField(default='', validators=[MinLengthValidator(240)],
                                   help_text='Описание должно быть не короче 240 символов', verbose_name='Описание')
    average_bill = models.SmallIntegerField(default=0, validators=[MinValueValidator(100), MaxValueValidator(10000)],
                                            help_text='Средний чек должен быть от 100 ₽ до 10 000 ₽',
                                            verbose_name='Средний чек')
    kitchen_first = models.ForeignKey('RestaurantKitchen', on_delete=models.CASCADE, null=True,
                                      related_name='%(app_label)s_%(class)s_first', verbose_name='Кухня (1)')
    kitchen_second = models.ForeignKey('RestaurantKitchen', on_delete=models.CASCADE, null=True, blank=True,
                                       related_name='%(app_label)s_%(class)s_second', verbose_name='Кухня (2)')
    kitchen_third = models.ForeignKey('RestaurantKitchen', on_delete=models.CASCADE, null=True, blank=True,
                                      related_name='%(app_label)s_%(class)s_third', verbose_name='Кухня (3)')
    # График работы
    monday = models.CharField(max_length=30, default='', validators=[RegexValidator(regex=RESTAURANT_DAY_REGEX)],
                              help_text=RESTAURANT_DAY_HELP_TEXT, verbose_name='Понедельник')
    tuesday = models.CharField(max_length=30, default='', validators=[RegexValidator(regex=RESTAURANT_DAY_REGEX)],
                               help_text=RESTAURANT_DAY_HELP_TEXT, verbose_name='Вторник')
    wednesday = models.CharField(max_length=30, default='', validators=[RegexValidator(regex=RESTAURANT_DAY_REGEX)],
                                 help_text=RESTAURANT_DAY_HELP_TEXT, verbose_name='Среда')
    thursday = models.CharField(max_length=30, default='', validators=[RegexValidator(regex=RESTAURANT_DAY_REGEX)],
                                help_text=RESTAURANT_DAY_HELP_TEXT, verbose_name='Четверг')
    friday = models.CharField(max_length=30, default='', validators=[RegexValidator(regex=RESTAURANT_DAY_REGEX)],
                              help_text=RESTAURANT_DAY_HELP_TEXT, verbose_name='Пятница')
    saturday = models.CharField(max_length=30, default='', validators=[RegexValidator(regex=RESTAURANT_DAY_REGEX)],
                                help_text=RESTAURANT_DAY_HELP_TEXT, verbose_name='Суббота')
    sunday = models.CharField(max_length=30, default='', validators=[RegexValidator(regex=RESTAURANT_DAY_REGEX)],
                              help_text=RESTAURANT_DAY_HELP_TEXT, verbose_name='Воскресенье')
    # Контакты
    address = models.CharField(max_length=255, verbose_name='Адрес')
    phone = models.CharField(max_length=20,
                             validators=[RegexValidator(regex=RESTAURANT_PHONE_REGEX)],
                             help_text='Пример: +7 346 200-00-00', verbose_name='Номер телефона')
    website = models.URLField(null=True, blank=True, verbose_name='Сайт')
    vkontakte = models.URLField(null=True, blank=True, verbose_name='ВКонтакте')
    instagram = models.URLField(null=True, blank=True, verbose_name='Инстаграм')
    email = models.EmailField(null=True, blank=True, verbose_name='Эл. почта')

class RestaurantKitchen(models.Model):
    name = models.CharField(max_length=30, unique=True, verbose_name='Наименование')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'кухня'
        verbose_name_plural = 'кухни'
        ordering = ['name']

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FulTupFul, 2019-07-01
@FulTupFul

The Restaurant table references RestaurantKitchen with an id. To get the value of the name field you need to refer to it

res = Restaurant.objects.latest()
res.kitchen_first.name

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question