django 일대다 조작

785 단어
Django 일대다 쿼리
  • 모델
    from django.db import models
    
    #       
    class User(models.Model):
        name = models.CharField(max_length=32)
    #           
    class Book(models.Model):
        title = models.CharField(max_length=32)
        us = models.Foreign('User',on_delete=models.CASCADE)
  • 보기 함수
    from django.shortcus import render,HttpResponse
    import models
    #       
    def index(request):
        user = models.User.objects.filter(id=1).first()
        uname = user.name #   
        book_list = [i.title for i in user.book_set.all()] #      
        return HttpResponse('ok')
    
    #       
    def index_b(request):
        book = Book.objects.filter(id=1).first()
        bname = book.title #   
        uname = book.us.name #   
        return HttpResponse('ok')
  • 좋은 웹페이지 즐겨찾기