0

我有以下型号:

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。这并不妨碍我为一个对象同时创建 aSpecificUserA和object:SpecificUserBUser

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,但是是否有一个可以捕获上述情况的检查?

4

0 回答 0