Graphene resolver for nested custom object

时间:2019-01-18 18:14:13

标签: python graphql graphene-python

I'm trying to use Graphene to model the following data: a MessageFrequency object, which represents the number of messages sent on a given date for a particular chat, and a MessageFrequencyRange object which represents the number of messages sent per day for a range of dates, all for a given chat.

I've tried creating custom classes and have been able to get the MessageFrequency object queryable by following this stackoverflow post, but I'm confused on how to get a nested custom object working. Below is my current code.

class MessageFrequency(graphene.ObjectType):

    chat_id   = graphene.Int()
    date      = graphene.Date()
    frequency = graphene.Int()


class MessageFrequencyRange(graphene.ObjectType):

    chat_id     = graphene.Int()
    start_date  = graphene.Date()
    end_date    = graphene.Date()
    frequencies = graphene.NonNull(graphene.List(graphene.NonNull(MessageFrequency)))

    def resolve_frequencies(self, info):
        return [
            # some method to instantiate a MessageFrequency object...
            # Query.resolve_message_frequency ?
        ]

class Query(graphene.ObjectType):

    message_frequency = graphene.Field(
        MessageFrequency,
        chat_id=graphene.Int(required=True),
        date=graphene.Date(required=True),
    )
    message_frequency_range = graphene.Field(
        MessageFrequencyRange,
        chat_id=graphene.Int(required=True),
    )

    def resolve_message_frequency(self, info, chat_id, date):
        # test data for now
        return MessageFrequency(
            chat_id=9000,
            date=date,
            frequency=1
        )

    def resolve_message_frequency_range(self, info):
        # Should be creating a MessageFrequencyRange object, but not sure how to fill
        # in the frequencies attribute which isn't a scalar
        return None

I'm not sure how I should be resolving the MessageFrequencyRange object inside Query, because it's more complicated than resolving a MessageFrequency object (as it has non scalar fields). I'm also not sure how to resolve the frequencies attribute of MessageFrequencyRange, I would think I should use the previously written resolver but I'm unsure on how exactly to call it.

Any help would be appreciated!

1 个答案:

答案 0 :(得分:0)

昨天我做了一个嵌套对象。我会尽力回答。如果您发布模型会很好。

<div>
  <ul>
    <li><a class="no-select gradient" href="../index.html">Acasă</a></li>
    <li><a class="no-select gradient active">Universul Observabil</a></li>
    <li><a class="no-select gradient" href="planets.html">Planete</a></li>
    <li><a class="no-select gradient" href="stars.html">Stele</a></li>
    <li><a class="no-select gradient" href="galaxies.html">Galaxii</a></li>
    <li><a class="no-select gradient" href="astrology.html">Istoria Astrologiei</a></li>
    <li><a class="no-select gradient" href="contact.html">Contact</a></li>
  </ul>
</div>