• Как вывести из модели связи с Foreign Key?

    winordie
    @winordie
    Лучшая документация -- исходники
    Snachala nado opredelit related_name dlya Vospitately.vospet_crushek
    class Vospitately(models.Model):
        fio = models.CharField(max_length=40)
        dolshnost = models.CharField(max_length=80, default='Должность..')
        image = models.ImageField()
        vospet_crushek = models.ForeignKey(Cruski', related_name='vospitately')
        def __str__(self):
            return self.fio

    Potom vo view mogno tak sdelat
    def kruzhki(request):
        q = Cruski.objects.all()
        return render(request,'krushki.html',{'kruzki':q})

    I nakonec v shablone pishem chto to po tipu takogo
    {% block kruzhki %}
    {% for krug in kruzki %}
    <p><b>{{ krug.name }}</b></p>
    {% for vospet in krug.vospitately.all %}
    <p> {{ vospet.fio }}</p>
    {% endfor %}
    <p>{{ krug.description }}</p>
    <p>{{ krug.price }}</p>
    {% endfor %}

    Vot i vse. Takim obrazom u nas vivoditsya krugki i vospitately kotorie v nis sostoyat.

    Kstati vam bi opredelitsya stoit kak pisat "кружки":
    - Cruski
    - vospet_crushek
    - kruzhki
    - kruzki
    - krushki.html
    Ответ написан
    3 комментария