Django 使 ContentType 变为非必需项
我有一个这样的模型:
class Auth(models.Model):
TYPES = (
('agent', 'Agent'),
('broker', 'Broker'),
)
user = models.ForeignKey(User, unique=True)
type = models.CharField(max_length=20, choices=TYPES)
applied = models.BooleanField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object=generic.GenericForeignKey('content_type', 'object_id')
每当我这样做的时候:
User.objects.create_user(username="myuser", password="myuser", email="myemail.com")
u = User.objects.get(username="myuser")
profile = Auth(user=u)
profile.save()
当然我会收到这个错误:
IntegrityError: (1048, "Column 'content_type_id' cannot be null")
对我来说,我无法避免使用内容类型,因为Auth是一个类,Broker和Agent类都是从这个类继承的,这让我可以做多个自定义的配置。
我在想有没有办法让内容类型不是必需的。
提前谢谢你们!
4 个回答
1
这里提到的 null=True
是在使用 Django 这个框架时,定义数据库字段的一个选项。简单来说,它的意思是这个字段可以留空,也就是可以没有值。比如说,如果你有一个用户的邮箱字段,你可以设置 null=True
,这样如果用户没有填写邮箱,这个字段就可以是空的,而不是强制要求填写。
1
你可以给这个字段设置一个默认值,比如用 default=...
,或者把它设置为 null=True
,这样就可以允许它为空。
5
content_type = models.ForeignKey(ContentType, null=True, blank=True)
null=True
让这个字段在数据模型中变成可选的,也就是说你可以不填这个字段。blank=True
则是让这个字段在使用管理员表单时也变成可选的,如果不加这个设置,你在表单里不填这个字段就会出现验证错误。