Django의 멀티플렉스 테이블, 조회 방식

3990 단어 Django
Django의 다중 쿼리 방식
from django.db import models

class Goods(models.Model):#  
    g_name = models.CharField(max_length=20)
    g_price = models.DecimalField(max_digits=5, decimal_places=2)
    gc = models.ForeignKey("Category", null=True, on_delete=models.SET_NULL)#gc   ,      

class Category(models.Model):#  
    c_name = models.CharField(max_length=20)


class Store(models.Model):#  
    s_name = models.CharField(max_length=30)
    s_detail = models.TextField(blank=True, null=True)
    sc = models.ManyToManyField("Category")#           

다대다증 삭제 검사는 동시에 일대다, 일대일로 적용되며, 소량의 매개 변수를 수정하면 된다
1. 
    
Store.objects.create(s_name="  A", s_detail="    ,    。。。。")
Out[2]: 

Store(s_name="  B", s_detail="   ").save()

    
Category.objects.create(c_name="    ")


Category(c_name="    ").save()

   (                ,                 )

    C      
Store.objects.create(s_name="  C").sc.add(*(Category.objects.all()))#         create  get

store = Store.objects.get(s_name="  C")
store.sc=(Category.objects.all())
store.save()


    D      
store = Store.objects.create(s_name="  D")
category = Category.objects.filter(c_name__in=["    ","    "])#    get,    all
store.sc.add(*category)#add     
store.sc.clear()#        

#              ,    
store = Store.objects.create(s_name="  E")
category = Category.objects.get(c_name="    ")
category.store_set.add(store)
       

            
stores = Store.objects.all()
category = Category.objects.get(c_name="    ")
category.store_set.add(*stores)

category.store_set.clear()#           
category.store_set.all().delete()#   store_set     
#      "     _set"   ,      QuerySet  ,     .add(),.remove(),.update(),.delete(),.clear()


2. 조사
(Store.objects.get(s_name="  C")).sc.all()
, ]>

Category.objects.filter(store__s_name="  C")
, ]>

#             
Store.objects.get(s_name="  C").sc.all()#  :    .       .    (all()/filter())
, ]>

    
Category.objects.filter(store__s_name="  C")
Out[25]: , ]>#    .filter(      __     ="    ")

     ,                  
(Category.objects.get(c_name="    ")).store_set.all()
, ]>

Store.objects.filter(sc=Category.objects.get(c_name="    "))
, ]>

Store.objects.filter(sc__c_name="    ")#filter(      __    ='    ')
, ]>

Store.objects.filter(sc=category)##filter  QuerySet,  :filter(      =      ),          ,              _    
, ]>


3. 삭제
         
s = Store.objects.get(s_name="  C")
c = Category.objects.all()
s.sc = ""
s.save()

s=Store.objects.get(s_name="  C")
c = Category.objects.all()
s.sc.remove(*c)

s = Store.objects.get(s_name="  C")
s.sc.clear()

           
           

s = Store.objects.all()
c = Category.objects.get(c_name="    ")
c.store_set.remove(*s)

c = Category.objects.get(c_name="    ")
c.store_set.clear()

#        
             

c=Category.objects.get(c_name="    ")
c.store_set.all().delete()

      
Store.objects.all().delete()

좋은 웹페이지 즐겨찾기