最近我正在写博客。帖子具有类别和子类别的地方。 这是我的模型。py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField
class Category(models.Model):
title = models.CharField(max_length=50, unique=True)
def __str__(self):
return f"{self.title}"
class SubCategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=50, unique=True)
def __str__(self):
return f"{self.title}"
class Author(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
phone_no = models.CharField(max_length=14)
details = models.TextField(null=True,blank=True)
def __str__(self):
return f"{self.name}"
class Post(models.Model):
author = models.ForeignKey(Author, default=1,blank=True,
null=True, on_delete=models.SET_DEFAULT)
category = models.ForeignKey(Category,on_delete=models.CASCADE,
null=True)
sub_category = models.ForeignKey(SubCategory,
on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=250)
featured_image = models.ImageField(
upload_to="post_featured_image",null=False )
content = RichTextUploadingField()
podcast = models.FileField(upload_to="post_podcast",
blank=True,null=True)
uploaded_on = models.DateTimeField(default=timezone.now)
viewed = models.IntegerField(default=0,editable=False)
def __str__(self):
return f"{self.title}"
现在,我可以从Django管理面板中为帖子选择类别和子类别。但是问题是我可以选择一个类别,任何子类别,即使该子类别都不是所选类别的子类别。因此,帖子有一个类别和一个子类别。但是子类别的父类别与帖子的类别不同。因此,我希望我只能选择那些子类别,这些子类别是我为帖子选择的所选类别的子类别。像下一个字段一样,必须依赖上一个字段。怎么做? 对不起,我的英语不好。谢谢。