Не выводит значение из трех таблиц Django
views.py
:
def viewUser(request):
"""Вывод просмотренных птиц пользователям."""
login = request.POST.get("login") # FIXME Не стоит передавать значение от пользователя всырой SQL-запрос.
sql_get = """SELECT Birds.name, Birds.PNG, Birds.feather_color, ViewedUser.DataTime
FROM User, Birds, ViewedBirds
WHERE User.login = %s
AND Birds.id_birds = ViewedBirds.id_birds
AND User.id_user = ViewedBirds.id_user
GROUP BY ViewedBirds.DataTime;""" % login
view = ViewedUser.objects.raw(sql_get) # FIXME может привести к SQL-инъекциям.
return render(request, 'viewUser.html/', {'view': view}, {'login': login})
Шаблон:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="viewUser"> {% csrf_token %}
<title>Просмотр птиц пользователем: {{ login }}</title>
<div class="abusteku-deagulus">
{% for bird in view %}
<div class="item">
<label></label>
<img src="/{{ bird.PNG }}" alt="" width="600" height="650">
<td>Птица: {{ bird.name }} Цвет: {{ bird.feather_color}}</td>
<td>Дата и время просмотра: {{ bird.DataTime }}</td>
{% endfor %}
</div>
</form>
</body>
</html>
models.py
:
class Birds(models.Model):
id_birds = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
id_user = models.ForeignKey('User', on_delete=models.PROTECT, null=True)
name = models.CharField(max_length=100, null=False, unique=True)
PNG = models.ImageField(upload_to='images')
feather_color = models.TextField(max_length=70, null=False)
class ViewedUser(models.Model):
id_view = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
id_birds = models.ForeignKey('Birds', on_delete=models.PROTECT, null=False, unique=True)
id_user = models.ForeignKey('User', on_delete=models.PROTECT, null=False)
DataTime = models.DateTimeField(null=False)
class User(models.Model):
id_user = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
full_name = models.CharField(max_length=100, null=False)
login = models.CharField(max_length=50, null=False, unique=True)
mail = models.EmailField(null=True)
password = models.CharField(max_length=100, null=False)
def __str__(self):
return self.name, self.PNG, self.feather_color, self.id_birds
И вот ошибка:
sql_get = """SELECT Birds.name, Birds.PNG, Birds.feather_color, ViewedUser.DataTime FROM birdsviews_user AS User, birdsviews_birds AS Birds, birdsviews_vieweduser AS ViewedUser WHERE User.login = %s AND Birds.id_birds = ViewedBirds.id_birds AND User.id_user = ViewedBirds.id_user GROUP BY ViewedBirds.DataTime;""" % login
""" По умолчанию Django выясняет имя таблицы базы данных путем присоединения к “маркировке приложения модели” – имя, в котором Вы использовали manage.py startapp – к имени класса модели, с подчеркиванием между ними. """