model.py
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=255)
class Post(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.title
view.py
from django.http import HttpResponse
from django.shortcuts import render
from OnetoOne.models import Post, Category
def test(request):
posts = Post.objects.all() # 所有文章
category = Category.objects.get(pk=1) # 獲取id為1的分類
posts = category.post_set.all() # 該分類下的所有文章(post_set) 可以被重寫
post_new = Post(title='Djang Book')
category.post_set.add(post_new, bulk=False)
# add方法在未保存的post_new情況下必須指定bulk=False
for post in posts:
print(post)
return HttpResponse('success')
重寫_set
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='the_posts')