在使用DjangoModelFormMutation保存之前添加用户到模型



我有一个DjangoLog模型,它与User有多对一

from django.db import models
class Log(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
...

我有一个Django表单的Log

from django.forms import ModelForm
class LogForm(ModelForm):
class Meta:
model = Log
exclude = ("user",)

我有一个石墨烯django突变,使Log创建

import graphene
from graphene_django import DjangoObjectType
from graphene_django.forms.mutation import DjangoModelFormMutation
class LogType(DjangoObjectType):
class Meta:
model = Log
fields = "__all__"
class CreateLogMutation(DjangoModelFormMutation):
log = graphene.Field(LogType)
class Meta:
form_class = LogForm

保存前如何设置Log.user为当前用户?对于Django基于类的视图,你可以这样做:

from django.views.generic import CreateView
class LogCreateView(CreateView):
model = Log
form_class = LogForm
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)

石墨烯-django是如何实现的?

覆盖perform_mutate并在那里添加用户。pefrom_mutate在Django的Form.is_valid之后被调用。

class CreateLogMutation(DjangoModelFormMutation):
log = graphene.Field(LogType)
class Meta:
form_class = LogForm
@classmethod
def perform_mutate(cls, form, info):
form.instance.user = info.context.user
return super().perform_mutate(form, info)

相关内容

  • 没有找到相关文章

最新更新