我希望能够在 django 中添加一些带有类别的博客文章和一些没有类别的博客文章。使用此模型,django admin 不会让我添加没有类别的博客文章。谢谢。
from django.db import models
from django.db.models import permalink
class Blog(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
body = models.TextField()
pub_date = models.DateField(db_index=True, auto_now_add=True)
# Many-to-one relationship.
category = models.ForeignKey('blog.Category')
class Category(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
最佳答案
像这样更新你的模型:
category = models.ForeignKey('blog.Category', blank=True, null=True)
blank=True
允许表单具有空白值。
null=True
允许数据库中存在空值。
编辑:这里是 documentation
关于python - 在 django 1.11 中添加没有类别的博客文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47340022/