S
S
sswwssww2020-09-26 14:57:43
Django
sswwssww, 2020-09-26 14:57:43

How to get a field with model id from another model in Django?

There are two models:

class Service(models.Model):
    """ Инстаграм; Вконтакте; Youtube и т.п. """
    name = models.CharField(verbose_name=u'Наименование', default='Разное', max_length=15, blank=False, null=False)

    class Meta:
        verbose_name = 'Сервис'
        verbose_name_plural = 'Сервисы'

    def __str__(self):
        return self.name


class Category(models.Model):
    """ Подписчики; Лайки; Просмотры и т.п. """
    service_id = models.ForeignKey(Service, verbose_name=u'Сервис', on_delete=models.CASCADE)
    name = models.CharField(verbose_name=u'Наименование', default='Разное', max_length=10)
    description = models.TextField(verbose_name=u'Описание', blank=True, null=True)

    class Meta:
        verbose_name = 'Категория'
        verbose_name_plural = 'Категории'

    def __str__(self):
        return self.name

And there is an index.html template:
<div class="col-xl-10 pb-5">
          {% for category in categories  %}
          <div class="category-item"  data-service="{{ category.service_id }}">
          </div>
          {% endfor %}
        </div>

- in which I'm only interested in category.service_id .
The question is the following, because I override __str__ methods in models in order for the admin panel to have a normal display of fields, it turns out that in category.service_id I have not the id field of the Service model, but the name field.
How to make it so that there is a normal display in the admin panel and the id and not the name is passed to the template?
Those. I need the Category > service_id to have the id of the Service and not its name field.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2020-09-26
@sswwssww

category.service_id.pk?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question