简体   繁体   中英

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM