我想知道是否可以在创建第一个模型时自动创建相关模型。
这是模特
class Team(models.Model):
name = models.CharField(max_length=55)
class TeamMember(models.Model):
team = models.ForeignKey('Team', on_delete=models.CASCADE, null=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False)
所以我想在“团队”模型上做类似的事情
class Team(models.Model):
name = models.CharField(max_length=55)
@on_new.do_this
TeamMember.team = self
TeamMember.user = request.user
TeamMember.save()
我试图找到有关此的任何文档。但是只发现了一些有关onetoonefields的例子。但是与此无关。
感谢任何帮助。干杯!
答案 0 :(得分:2)
我假设您正在使用表单来创建团队。
没有当前用户(通过TeamMember
),无法直接创建request
实例。 request
仅在视图中可用(除非您使用特殊的中间件或第三方库来访问它),因此我们可以通过覆盖模型表单的save
方法来发送它并创建用户。< / p>
所以您可以尝试这样:
# Override the model form's save method to create related object
class TeamForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(TeamForm, self).__init__(*args, **kwargs)
class Meta:
model = Team
def save(self, **kwargs):
user = self.request.user
instance = super(TeamForm, self).save(**kwargs)
TeamUser.objects.create(team=instance, user=user)
return instance
并在“视图”中使用此表单:
# Update get_form_kwargs methods in create view
class TeamCreateView(CreateView):
form_class = TeamForm
template = 'your_template.html'
def get_form_kwargs(self):
kw = super(TeamCreateView, self).get_form_kwargs()
kw['request'] = self.request
return kw
(来自注释的 )如果Team
中有用户FK可用,则可以通过覆盖save
方法使用它来创建TeamMember。尝试这样:
class Team(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL)
name = models.CharField(max_length=55)
def save(self, *args, **kwargs): # <-- Override
instance = super(Team, self).save(*args, **kwargs)
TeamMember.objects.create(user=instance.user, team=instance)
return instance