我有一个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)