Проблема с выводом информации из бд
Такая проблема: есть раздел с жилыми комлексами, у каждого жк есть отдельная страничка, на которой находятся карточки с домами. Хочу, чтобы при нажатии на карточку дома, выводилась информация этого дома из бд. Но при выборе любого дома выводится одна и та же информация (самого первого дома). Как это исправить?
Понимаю, что проверка {% if ap.house == house %} в шаблоне очень глупая( и предполагаю, что исправлять нужно вьюху
Шаблон
<div class="house-section">
<h2 class="text-left">Дома</h2>
<div class="h-cards-wrapper">
{% for house in houses %}
<div class="h-card">
<div class="h-card-info">
<p class="house-title">Дом {{ house.house_number }}</p>
<button class="btn btn-primary read-more h-btn" id="showCard" onClick="viewHouseCard()" >
Подробнее
</button>
</div>
</div>
<div class="house-card" id="house-card">
<button class="closeCard" onClick="closeHouseCard()">
<i class="fa fa-times" aria-hidden="true"></i>
</button>
<div class="card-content">
<h1 class="white h-card-title">Дом {{ house.house_number }}</h1>
<table class="table-container">
<tr>
<th>Номер <br> квартиры</th>
<th>Этаж</th>
<th>Кол-во <br> комнат</th>
<th>Площадь</th>
<th>Отделка</th>
<th>Цена <br> за м2</th>
<th>Цена за <br> объект</th>
<th>Планировка</th>
</tr>
{% for ap in apartments %}
{% if ap.house == house %}
<tr>
<td>{{ap.apartment_number}}</td>
<td>{{ap.level}}</td>
<td>{{ap.room}}</td>
<td>{{ap.square}}</td>
<td>{{ap.finishing}}</td>
<td>{{ap.price_m}}</td>
<td>{{ap.price_total}}</td>
<td><button class="view-plan" onClick="viewHousePlan()"><i class="fa fa-eye" aria-hidden="true"></i></button></td>
</tr>
{% endif %}
{% endfor %}
</table>
</div>
</div>
{% endfor %}
</div>
</div>
views.py
class ComplexDetailView(DetailView):
active = ['service']
model = Complex
template_name = 'service/complex.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['gallery'] = ComplexGallery.objects.filter(complex=context['complex'])
context['houses'] = House.objects.filter(complex=context['complex'])
context['apartments'] = Apartment.objects.all()
return context
models.py
from django.db import models
from .utils import *
class Complex(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(blank=True)
description = models.TextField()
img = models.ImageField(upload_to='complex/', blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = from_cyrillic_to_eng(str(self.name))
super().save(*args, **kwargs)
def __str__(self):
return '%s' % self.name
class ComplexGallery(models.Model):
complex = models.ForeignKey(Complex, on_delete=models.CASCADE, blank=True)
gal_img = models.ImageField(upload_to='complex/gallery/', blank=True)
def __str__(self):
return '%s' % self.complex.name
class House(models.Model):
complex = models.ForeignKey(Complex, on_delete=models.CASCADE, blank=True)
house_number = models.IntegerField()
def __str__(self):
return '%s' % self.house_number
class Apartment(models.Model):
house = models.ForeignKey(House, on_delete=models.CASCADE, blank=True)
apartment_number = models.IntegerField()
level = models.IntegerField()
room = models.IntegerField()
square = models.FloatField()
finishing = models.BooleanField(default=False)
price_m = models.DecimalField(max_digits=7, decimal_places=1)
price_total = models.DecimalField(max_digits=10, decimal_places=1)
plan_img = models.ImageField(upload_to='complex/apartment/', blank=True)
def __str__(self):
return '%s' % self.apartment_number
Ответы (1 шт):
Автор решения: cauf
→ Ссылка
У вас берется информация о вообще всех квартирах во всех домах всех комплексов. А все потому, что вы забыли отфильтровать запрос к объекту Apartment. Судя по всему, view должна выглядеть как-то так:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['gallery'] = ComplexGallery.objects.filter(complex=context['complex'])
context['houses'] = House.objects.filter(complex=context['complex'])
# здесь формируется словарь id_дома: список_квартир
context['apartments'] = {h.pk: Apartment.objects.filter(house = h) for h in context['houses']}
return context
