我是 GraphQL 的相对新手,我正在尝试进行这样的查询
{
user(username: "Jon") {
name
last_lame
username
posts(in_draft : true) {
title
text
in_draft
update_at
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想过滤用户在草稿中的帖子列表
我可以进行查询的唯一方法是通过模型的关系,但无法过滤草稿中的帖子。一对多
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
last_lame = Column(String)
username = Column(String)
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
title = Column(String)
text = Column(String)
in_draft = Column(Boolean)
post_id = Column(Integer, ForeignKey('user.id'))
posts = relationship("User", backref='posts')
Run Code Online (Sandbox Code Playgroud)
有了这种关系,我用“backref = 'posts'”显示了帖子节点
我的对象:
class User(SQLAlchemyObjectType):
"""User Object."""
class Meta:
model = UserModel …Run Code Online (Sandbox Code Playgroud) 我目前为我的项目定义了以下突变:
我的类PlanetAttribute 用于定义用作突变输入的石墨烯字段
class PlanetAttribute:
name = graphene.String(required=True, description="Name of the planet.")
rotation_period = graphene.String(default_value="unknown", description="Rotation period of the planet.")
orbital_period = graphene.String(default_value="unknown", description="Orbital period of the planet.")
diameter = graphene.String(default_value="unknown", description="Diameter of the planet.")
climate = graphene.String(default_value="unknown", description="Climate period of the planet.")
gravity = graphene.String(default_value="unknown", description="Gravity of the planet.")
terrain = graphene.String(default_value="unknown", description="Terrain of the planet.")
surface_water = graphene.String(default_value="unknown", description="Surface water of the planet.")
population = graphene.String(default_value="unknown", description="Population of the planet.")
url = graphene.String(default_value="unknown", description="URL of the planet …Run Code Online (Sandbox Code Playgroud) 我已经实现了 graphql 并且我正在迁移到中继。我已经为每个表创建了一个 uuid,名为“id”。我的应用程序我发现了这个 github 线程,它讨论了可能会更改规范,但感觉就像一个兔子洞。
有没有一种简单的方法可以将我自己的自定义 ID 与中继一起使用?
我对 Graphene 非常陌生,正在测试它,看看是否可以将它用于具有复杂查询的 Django 项目。为了测试它,我尝试使用以下模型创建一个电子商务
class Sku(models.Model):
name = models.CharField(max_length=100)
class Product(models.Model):
name = models.CharField(max_length=100)
class ProductSku(models.Model):
sku = models.ForeignKey(Sku, related_name='product_sku', on_delete=models.CASCADE)
product = models.ForeignKey(Product, related_name='product_sku', on_delete=models.CASCADE)
price = models.IntegerField()
Run Code Online (Sandbox Code Playgroud)
正如您在此处看到的,Product 和 Sku 使用 ProductSku 模型具有多对多关系
使用 Graphene 的文档我创建了以下架构
class SkuNode(DjangoObjectType):
class Meta:
model = Sku
class ProductNode(DjangoObjectType):
class Meta:
model = Product
class ProductSkuNode(DjangoObjectType):
class Meta:
model = ProductSku
class Query(graphene.ObjectType):
all_products = graphene.List(ProductNode, name=graphene.String())
product = graphene.Field(ProductNode, id=graphene.Int())
def resolve_all_products(self, info, **args):
name = args.get('name')
if name is …Run Code Online (Sandbox Code Playgroud) 我正在使用带有graphql的rest框架序列化程序。我正在尝试在用户注册时创建用户,并根据用户在创建帐户时选择的角色创建个人资料。为此,我添加了一个序列化器层,但是当我serializer.save在 mutate 函数中使用时,不会调用序列化器创建函数。为什么呢?
这是我的做法
class Register(graphene.Mutation):
"""
Mutation to register a user
"""
class Arguments:
email = graphene.String(required=True)
password = graphene.String(required=True)
password_repeat = graphene.String(required=True)
role = graphene.String(required=True)
success = graphene.Boolean()
errors = graphene.List(graphene.String)
email = graphene.String()
def mutate(self, info, email, password, password_repeat, role):
if password == password_repeat:
try:
serializer = RegistrationSerializer(data={
'email': email,
'password': password,
'is_active': False,
'role': role,
})
if serializer.is_valid():
print("valid")
user = serializer.save()
# user.set_password(password)
print ("user is ###########", user)
# user = UserModel.objects.create(
# …Run Code Online (Sandbox Code Playgroud) Graphene-Django 的文档几乎解释了如何创建和更新对象。但是如何删除呢?我可以想象查询看起来像
mutation mut{
deleteUser(id: 1){
user{
username
email
}
error
}
}
Run Code Online (Sandbox Code Playgroud)
但是我怀疑正确的方法是从头开始编写后端代码。
我有一个带有继电器和过滤器的石墨烯接口。它工作得很好,但我想添加 order_by 选项。我的对象看起来像:
class FooGQLType(DjangoObjectType):
class Meta:
model = Foo
exclude_fields = ('internal_id',)
interfaces = (graphene.relay.Node,)
filter_fields = {
"id": ["exact"],
"code": ["exact", "icontains"],
}
connection_class = ExtendedConnection
class Query(graphene.ObjectType):
foo = DjangoFilterConnectionField(FooGQLType)
Run Code Online (Sandbox Code Playgroud)
ExtendedConnection 不应该相关,但是:
class ExtendedConnection(graphene.Connection):
class Meta:
abstract = True
total_count = graphene.Int()
def resolve_total_count(root, info, **kwargs):
return root.length
Run Code Online (Sandbox Code Playgroud)
这使我可以像foo(code_Icontains:"bar"). 根据石墨烯文档,我应该为此在 FilterSet 中使用 OrderingFilter 。我觉得有点烦人,因为过滤器应该是自动的,但如果我这样做:
class FooGQLFilter(FilterSet):
class Meta:
model = Foo
order_by = OrderingFilter(
fields=(
('code', 'code'),
('lastName', 'last_name'),
('otherNames', 'other_names'),
)
) …Run Code Online (Sandbox Code Playgroud) 所以我的模型看起来像
class Abcd(models.Model):
name = models.CharField(max_length=30, default=False)
data = models.CharField(max_length=500, blank=True, default=False)
Run Code Online (Sandbox Code Playgroud)
需要在查询时传递一个字典,它不是模型的一部分,查询是
query {
allAbcd(Name: "XYZ") {
edges {
node {
Data
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何通过查询传递这样一个自定义字段?
此自定义字段对于其他流程目的是必需的。
我正在使用 graphene-django 作为 api。我正在尝试创建一个突变来创建一个具有公司外键的品牌。当我变异时,我收到以下错误“'input'是 print() 的无效关键字参数”。我无法弄清楚为什么会抛出这个错误。
这是我的突变
class BrandInput(graphene.InputObjectType):
company = graphene.List(CompanyInput)
name = graphene.String()
website = graphene.String()
description = graphene.String()
country = graphene.String()
city = graphene.String()
address = graphene.String()
class CreateBrand(graphene.Mutation):
class Arguments:
input = BrandInput(description="These fields are required", required=True)
class Meta:
description = "Create Brand Mutation"
errors = graphene.String()
brand = graphene.Field(BrandNode)
@staticmethod
def mutate(root, info, **args):
print('args', args, **args)
if not info.context.user.is_authenticated:
return CreateBrand(errors=json.dumps('Please Login to list your brand'))
try:
company = models.Company.objects.get(slug=args.get('input')['company'])
if company:
brand = …Run Code Online (Sandbox Code Playgroud) mutation{
createPayment(p_obj={"bob": 80, "job": 100}){
<fields here>
}
}
Run Code Online (Sandbox Code Playgroud)
我能找到的是接受对象列表作为输入,例如:
[ {username: "bob", "amount": 80}, {username: "job", "amount": 100} ]
Run Code Online (Sandbox Code Playgroud)