[英]How to combine queries in django
i am creating a website where user will download videos, now i want to query the artist and it's videos, i already have one to many field but i have no idea how to do in views.py我正在创建一个用户将下载视频的网站,现在我想查询艺术家及其视频,我已经有一对多字段但我不知道如何在 views.py
this is my models这是我的模型
from django.db import models
from embed_video.fields import EmbedVideoField
# Create your models here.
class Video(models.Model):
video_author = models.CharField(default='Bongo Media', max_length=20)
video_title = models.CharField(max_length=100)
video_file = models.FileField(blank=True)
video_image = models.ImageField(default='image.png')
video_embed_link = EmbedVideoField(blank=True)
video_descriptions = models.TextField(max_length=100, blank=True)
video_pubdate = models.DateTimeField(auto_now=True)
is_recommended = models.BooleanField(default=False)
def __str__(self):
return self.video_title
class Artist(models.Model):
artist_picture = models.ImageField(upload_to='media')
artist_name = models.CharField(max_length=100)
artist_songs = models.ForeignKey(Video, on_delete=models.CASCADE)
def __str__(self):
return self.artist_name
and this is my views.py这是我的views.py
from django.shortcuts import render, get_object_or_404
from .models import Video, Artist
# Create your views here.
def home(request):
artist = Artist.objects.all()
videos = Video.objects.all().order_by('-video_pubdate')
context = {
'videos': videos,
'artist': artist
}
return render(request, 'index.html', context)
def detail(request, pk):
video_detail = get_object_or_404(Video, pk=pk)
context = {
'video_detail': video_detail
}
return render(request, 'detail.html', context)
Add related_name
in the field在字段中添加related_name
artist_songs = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='artists')
and you can query like你可以像这样查询
Video.objects.filter(artists__id=artist.id)
but that doesn't make sense if artist fk to video, you should change to many_to_many
但是如果艺术家 fk 到视频,那没有意义,你应该改为many_to_many
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.