我看过很多关于外键突变的文章,但没有任何帮助。
我需要使用 django 模型 Person 创建一个人,该人的地址是 Address 模型的外键。一个人需要一个地址!
我在 django 中的模型是:
from django.db import models
class Address(models.Model):
class Meta:
verbose_name_plural = "Addresses"
number = models.CharField(max_length=4)
street = models.CharField(max_length=100)
city = models.CharField(max_length=100)
postcode = models.CharField(max_length=7)
class Person(models.Model):
class Meta:
verbose_name_plural = "Persons"
avatar = models.ImageField(upload_to='images/avatars/')
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
personal_image = models.ImageField(upload_to='images/personal_images/')
def get_fullname(self):
return self.first_name + ' ' + self.last_name
我的模式中的突变是:
class AddressInput(graphene.InputObjectType):
number = graphene.String(required=True)
street = graphene.String(required=True)
city = graphene.String(required=True)
postcode = graphene.String(required=True)
class CreatePerson(graphene.Mutation):
class Arguments:
avtr = Upload(required=False)
fname = graphene.String(required=True)
lname = graphene.String(required=True)
addr = graphene.Argument(AddressInput, required=False)
pimage = Upload(required=False)
person = graphene.Field(PersonType)
def mutate(self, info, avtr, fname, lname, addr, pimage):
person = Person(
avatar=avtr,
firstName=fname,
lastName=lname,
address=addr,
personalImage=pimage
)
return CreatePerson(person=person)
class Mutations(graphene.ObjectType):
create_person = CreatePerson.Field()
我正在使用 GraphiQL 进行测试,我的变异 atm 如下所示:
mutation createPerson {
createPerson(avtr: None, fname: "Bob", lname: "Diamond", addr: {number: "10", street: "Hormond Avenue", city: "Shrewsbury", postcode: "N7 9RF"}, pimage: None) {
person {
firstName
lastName
}
}
}
我得到的输出是:
{
"errors": [
{
"message": "Cannot assign \"{'number': '10', 'street': 'Hormond Avenue', 'city': 'Shrewsbury', 'postcode': 'N7 9RF'}\": \"Person.address\" must be a \"Address\" instance.",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"createPerson"
]
}
],
"data": {
"createPerson": null
}
}