当使用相关对象管理器的
当我使用以下方法时:
create
方法时,Django如何分配外键?我之所以问是因为当我创建自己的create
方法时,外键不会自动设置。这里有一个例子:class ModelAQuerySet(models.QuerySet):
def create(self, **kwargs):
print('create:')
print(kwargs)
return super().create(**kwargs)
def create_with_other_options(self, **kwargs):
print('create_with_other_options:')
print(kwargs)
return self.create(**kwargs)
class ModelABaseManager(models.Manager):
use_for_related_fields = True
ModelAManager = ModelABaseManager.from_queryset(ModelAQuerySet)
class ModelA(models.Model):
objects = ModelAManager()
user = models.ForeignKey('User', related_name='modela_set')
当我使用以下方法时:
>>> u = User.object.get(...)
>>> a1 = u.modela_set.create() # it works, user is set automatically
create:
{..., 'user': <User: id:1 email:"...">}
>>> a2 = u.modela_set.create_with_other_options() # it does not work, user is not set automatically
create_with_other_options:
{}
IntegrityError: null value in column "user_id" violates not-null constraint