如何重新排序 Django-Graphene 子查询?

How to reorder Django-Graphene sub-query?

我正在尝试根据我的 ProductLandingpageImage 模型上的 'order' 字段重新排序我的 ProductLandingPageImageNode。

如果这是一个直接查询,我可以编写一个解析方法,但我无法找出在子查询上如何实现。

主要查询:

class Query(graphene.ObjectType):
  class Meta:
    interfaces = [relay.Node, ]

  product_oscar = graphene.List(ProductNode)
  productByID = DjangoFilterConnectionField(ProductNode)


  def resolve_product_oscar(self, info, **kwargs):
    return Product.objects.all()

产品节点:

class ProductNode(DjangoObjectType):
  class Meta:
    model = Product
    interfaces = (relay.Node, )
    filter_fields = {
      "slug" : ['iexact']
    }

PRODUCTLANDINGPAGEIMAGENODE:

class ProductLandingpageImageNode(DjangoObjectType):
  class Meta:
    model = ProductLandingpageImage
    interfaces = (relay.Node, )

如何解决?


LANDINGPAGEIMAGE 模型请求:

class AbstractProductLandingpageImage(models.Model):
  """
    A landingpageimage of a product
  """
  product = models.ForeignKey(
    'catalogue.Product',
    on_delete=models.CASCADE,
    related_name='landingpage_image',
    verbose_name=_("Product landingpage"))
  date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  original = models.ImageField(
    _("Landingpage original"), upload_to=settings.OSCAR_IMAGE_FOLDER, max_length=255, blank=True)

  ORDER_CHOICES = (
    (1, 1),
    (2, 2),
    (3, 3),
    (4, 4),
    (5, 5),
    (6, 6),
  )

  order = models.PositiveIntegerField(default=1, choices=ORDER_CHOICES, blank=True)

class Meta:
    abstract = True
    app_label = 'catalogue'
    # Any custom models should ensure that this ordering is unchanged, or
    # your query count will explode. See AbstractProduct.primary_image.
    ordering = ["order"]
    verbose_name = _('Product landingpage image')
    verbose_name_plural = _('Product landingpage images')

Meta 中的默认排序不知何故不起作用。当我 Graphql 查询订单值不是 return "1, 2, 3..." 而是 "A_1, A_2..."

时,也很奇怪

也许是这样的。由于您没有列出您的产品型号,我只是在引用图像的产品上编造了字段名称,因此您应该重命名它。如果产品和图像之间存在多对一关系,您可能需要不同的字段名称。

import graphene
from graphene.django.types import DjangoObjectType

class ProductNode(DjangoObjectType):
    name_of_your_image_field = graphene.Field(ProductLandingpageImageNode)

    class Meta:
        model = Product
        ... other Meta data


    def resolve_name_of_your_image_field(self, info):  # rename to match field
        # Put the code that returns a single ProductLandingpageImage instance here
        # graphene-django will convert your ProductLandingPageImage instance into a ProductLandingpageImageNode

这是针对 return 单个 ProductLandingPageIMage 的。如果要return多个实例,则将字段定义改为列表

    name_of_your_image_field = graphene.List(ProductLandingpageImageNode)

然后在您的解析器中 return 多个 ProductLandingPageImage 实例——例如按您希望的方式排序的查询集。