1. 程式人生 > >057:表關係之一對多

057:表關係之一對多

表關係:
表之間的關係都是通過外來鍵來進行關聯的。而表之間的關係,無非就是三種關係:一對一、一對多(多對一)、多對多等。以下將討論一下三種關係的應用場景及其實現方式。

一對多:
1. 應用場景:比如文章和作者之間的關係。一個文章只能由一個作者編寫,但是一個作者可以寫多篇文章。文章和作者之間的關係就是典型的多對一的關係。
2. 實現方式:一對多或者多對一,都是通過 ForeignKey 來實現的。還是以文章和作者的案例進行講解。

models.py:

class Category(models.Model):
    username = models.CharField(max_length=128)
    
def __str__(self): return "<Category: name:%s>" % self.username class Article(models.Model): title = models.CharField(max_length=128) content = models.TextField() category = models.ForeignKey("Category", on_delete=models.CASCADE) # category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='articles')
# user = models.ForeignKey('cms.user',on_delete=models.CASCADE, null=True) def __str__(self): return "<Article: title:%s, content:%s>" % (self.title, self.content)

views.py:

def index(request):
   # 第一種新增文章資料方式
# category = Category(username="張三") # category.save()
# # article = Article(title='1111', content='fuck you') # article.category = category # article.save() # print(article.category.username) # article.category.username = '李四' # print(article.category.username)    # 獲取某類下的所有文章 category = Category.objects.get(pk=2) aritcles = category.article_set.all() # 誰引用了表的欄位作為外來鍵,就設定這個 "模型的_set" 方法獲取資料 # aritcles = category.articles.all() #如果模型中設定了: related_name='articles'
   for article in aritcles: 
    
print(article)
   # 第二種新增文章資料方式 article1
= Article(title='xyz', content="778899") category.article_set.add(article1,bulk=False) # category.articles.add(article1,bulk=False) #如果模型中設定了: related_name='articles'
   return HttpResponse('success')