我有以下型号:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class CommonUser(models.Model):
user = models.OneToOneField(User)
field = models.CharField(max_length=20)
class SpecificUserA(models.Model):
user = models.OneToOneField(CommonUser)
field_a = models.CharField(max_length=20)
class SpecificUserB(models.Model):
user = models.OneToOneField(CommonUser)
field_b = models.CharField(max_length=20)
这使我可以在SpecificUserA
和SpecificUserB
之间共享信息。这不会阻止我为一个SpecificUserA
对象创建SpecificUserB
和User
对象:
u = User.objects.create_user(username='user1')
u.save()
u.commonuser = CommonUser(field="user1 field data")
u.commonuser.save()
u.commonuser.specificusera = SpecificUserA(field_a="user1 field_a data")
u.commonuser.specificusera.save()
# how can I prevent this?
u.commonuser.specificuserb = SpecificUserB(field_b="user1 field_b data")
u.commonuser.specificuserb.save()
我知道在创建User
对象之前,我可以设置条件来检查具有特定用户名的Specific
对象是否存在,但是是否有检查可以捕获上述场景?