### Setup Django Database and Load Example Data Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook/README.md Applies database migrations, loads example data from the 'ingredients' fixture, and prompts for creating an administrative user for the Django project. ```bash ./manage.py migrate ./manage.py loaddata ingredients ./manage.py createsuperuser ``` -------------------------------- ### Setup Django Project and Install Graphene-Django Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Commands to create a Django project and app, set up a virtual environment, and install Django and Graphene-Django for development. ```bash mkdir cookbook cd cookbook virtualenv env source env/bin/activate # On Windows use `env\Scripts\activate` pip install django pip install graphene_django django-admin.py startproject cookbook . # Note the trailing '.' character cd cookbook django-admin.py startapp ingredients ``` -------------------------------- ### Create a Basic Graphene Schema Source: https://github.com/graphql-python/graphene-django/blob/main/docs/installation.rst Illustrates a minimal Graphene schema definition in a schema.py file. This example includes a simple Query object with a single 'hello' field that returns a default string value. ```python import graphene class Query(graphene.ObjectType): hello = graphene.String(default_value="Hi!") schema = graphene.Schema(query=Query) ``` -------------------------------- ### Setup Django Project and Install Dependencies Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This snippet provides the necessary bash commands to create a new Django project, set up a virtual environment, install Django and Graphene-Django, and create a new Django app within the project structure. ```bash # Create the project directory mkdir cookbook cd cookbook # Create a virtualenv to isolate our package dependencies locally virtualenv env source env/bin/activate # On Windows use `env\Scripts\activate` # Install Django and Graphene with Django support pip install django graphene_django # Set up a new project with a single application django-admin startproject cookbook . # Note the trailing '.' character cd cookbook django-admin startapp ingredients ``` -------------------------------- ### Setup Django Database and Admin User Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook-plain/README.md Executes Django database migrations to set up the schema, loads initial example data for 'ingredients', and creates a superuser account for administrative access to the Django admin interface. ```bash ./manage.py migrate # Load some example data ./manage.py loaddata ingredients # Create an admin user (useful for logging into the admin UI # at http://127.0.0.1:8000/admin) ./manage.py createsuperuser ``` -------------------------------- ### Install Python Project Dependencies Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook-plain/README.md Installs all required Python packages and libraries for the project by reading them from the 'requirements.txt' file using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Start Django Development Server Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook-plain/README.md Launches the Django development server, making the application accessible locally, typically at http://127.0.0.1:8000/, and enabling interaction with the GraphQL endpoint. ```bash ./manage.py runserver ``` -------------------------------- ### Install Graphene-Django via pip Source: https://github.com/graphql-python/graphene-django/blob/main/docs/installation.rst Installs the Graphene-Django library using pip. It is strongly recommended to pin against a specific version to avoid potential breaking changes introduced by new releases. ```bash pip install graphene-django ``` -------------------------------- ### Clone Graphene-Django Example Project Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook-plain/README.md Clones the Graphene-Django repository from GitHub and navigates into the 'cookbook-plain' example directory, which contains the project source code. ```bash git clone https://github.com/graphql-python/graphene-django.git cd graphene-django/examples/cookbook-plain ``` -------------------------------- ### Start Django Development Server Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook/README.md Starts the Django development server, making the application accessible via a web browser, typically at http://127.0.0.1:8000/. ```bash ./manage.py runserver ``` -------------------------------- ### Install Python Project Dependencies Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook/README.md Installs all required Python packages listed in the 'requirements.txt' file into the currently active virtual environment. ```bash pip install -r requirements.txt ``` -------------------------------- ### Clone Graphene-Django Repository and Navigate Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook/README.md Clones the Graphene-Django repository from GitHub and navigates into the 'cookbook' example project directory. ```bash git clone https://github.com/graphql-python/graphene-django.git cd graphene-django/examples/cookbook ``` -------------------------------- ### Add GraphQL URL Pattern to Django urls.py Source: https://github.com/graphql-python/graphene-django/blob/main/docs/installation.rst Defines a URL path for the GraphQL endpoint in your Django project's urls.py. This example uses GraphQLView.as_view() with graphiql enabled, providing an interactive API browser. This configuration is suitable for Django 2.2 and above. ```python from django.urls import path from graphene_django.views import GraphQLView urlpatterns = [ # ... path("graphql", GraphQLView.as_view(graphiql=True)), ] ``` -------------------------------- ### Run Django Development Server Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Starts the Django development server, making the application accessible at `http://127.0.0.1:8000/` for testing the GraphQL API. ```bash $ python ./manage.py runserver ``` -------------------------------- ### Configure Graphene-Django in Django INSTALLED_APPS Source: https://github.com/graphql-python/graphene-django/blob/main/docs/installation.rst Adds 'graphene_django' to the INSTALLED_APPS list within your Django project's settings.py file. 'django.contrib.staticfiles' is also included as it is required for the GraphiQL interface. ```python INSTALLED_APPS = [ ... "django.contrib.staticfiles", # Required for GraphiQL "graphene_django" ] ``` -------------------------------- ### Install Django Filter Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Installs the `django-filter` library, which is required for the tutorial's use of `filter_fields` functionality. ```bash pip install django-filter ``` -------------------------------- ### Set Up Graphene-Django Development Environment Source: https://github.com/graphql-python/graphene-django/blob/main/CONTRIBUTING.md Installs all necessary development dependencies for the graphene-django project after cloning the repository, preparing it for local development. ```sh make dev-setup ``` -------------------------------- ### Install Graphene-Django Documentation Dependencies Source: https://github.com/graphql-python/graphene-django/blob/main/CONTRIBUTING.md Navigates into the documentation directory and installs the required Python packages for building the project's documentation using pip. ```sh cd docs pip install -r requirements.txt ``` -------------------------------- ### Install django-filter and Add to Django INSTALLED_APPS Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst Instructions for installing the `django-filter` library using pip and adding `django_filters` to the `INSTALLED_APPS` list in Django's `settings.py` file, which is a prerequisite for Graphene-Django filtering. ```bash # You'll need to install django-filter pip install django-filter>=2 ``` ```python INSTALLED_APPS = [ # ... "django_filters", ] ``` -------------------------------- ### Configure requirements.txt for Local Graphene-Django Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook-plain/README.md Modifies the project's 'requirements.txt' file to point to a local development version of 'graphene-django' instead of the PyPI package, facilitating testing of local changes to the library. ```text ../../ # graphene-django ``` -------------------------------- ### Install Graphene-Django via pip Source: https://github.com/graphql-python/graphene-django/blob/main/README.md This command installs the Graphene-Django library using pip, the Python package installer. It's the foundational step to integrate Graphene with a Django project, ensuring all necessary dependencies are met. ```sh pip install graphene-django ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook-plain/README.md Initializes a new Python virtual environment named 'env' to isolate project dependencies and then activates it, ensuring that subsequent Python commands use this isolated environment. ```bash virtualenv env source env/bin/activate ``` -------------------------------- ### Create and Activate Python Virtual Environment Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook/README.md Creates a new Python virtual environment named 'env' using virtualenv and then activates it, isolating project dependencies. ```bash virtualenv env source env/bin/activate ``` -------------------------------- ### Define Graphene Schema Location in Django Settings Source: https://github.com/graphql-python/graphene-django/blob/main/docs/installation.rst Configures the 'SCHEMA' setting for Graphene within your Django project's settings.py. This specifies the Python path to the Graphene Schema object that your project will use. ```python GRAPHENE = { "SCHEMA": "django_root.schema.schema" } ``` -------------------------------- ### Example GraphQL Response for Category by Name with Relations Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This JSON snippet provides an example of the data returned by the `categoryByName` GraphQL query. It includes the category's details and a nested array of its related ingredients, demonstrating relational data retrieval. ```json { "data": { "categoryByName": { "id": "1", "name": "Dairy", "ingredients": [ { "id": "1", "name": "Eggs" }, { "id": "2", "name": "Milk" } ] } } } ``` -------------------------------- ### Build Graphene-Django HTML Documentation Source: https://github.com/graphql-python/graphene-django/blob/main/CONTRIBUTING.md Generates the HTML version of the project documentation using Sphinx, typically after installing all documentation dependencies. ```sh make html ``` -------------------------------- ### Example GraphQL Response for All Ingredients Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This JSON snippet illustrates the expected data structure returned by the `allIngredients` GraphQL query. It shows a list of ingredient objects, each containing an `id` and `name` field. ```json { "data": { "allIngredients": [ { "id": "1", "name": "Eggs" }, { "id": "2", "name": "Milk" }, { "id": "3", "name": "Beef" }, { "id": "4", "name": "Chicken" } ] } } ``` -------------------------------- ### Exempt GraphQL Endpoint from CSRF Protection Source: https://github.com/graphql-python/graphene-django/blob/main/docs/installation.rst Modifies the GraphQL URL pattern in urls.py to exempt the endpoint from Django's CSRF protection using the csrf_exempt decorator. This is an alternative approach if you do not wish to pass CSRF tokens with every API request. ```python # urls.py from django.urls import path from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView urlpatterns = [ # ... path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True))), ] ``` -------------------------------- ### Define a Simple Django Post Model Source: https://github.com/graphql-python/graphene-django/blob/main/docs/authorization.rst This snippet defines a basic Django `Post` model with fields for title, content, publication status, and an owner, serving as the example model for demonstrating authorization techniques in Graphene-Django. ```python from django.db import models class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() published = models.BooleanField(default=False) owner = models.ForeignKey('auth.User') ``` -------------------------------- ### Include All Model Fields in DjangoObjectType Source: https://github.com/graphql-python/graphene-django/blob/main/docs/queries.rst This example demonstrates how to include all fields from a Django model in a `DjangoObjectType` by setting the `fields` attribute to the special value `"__all__"`. ```python from graphene_django import DjangoObjectType from .models import Question class QuestionType(DjangoObjectType): class Meta: model = Question fields = "__all__" ``` -------------------------------- ### Example GraphQL Query for Ordering Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst This GraphQL query illustrates how to use the `orderBy` argument to sort results when an `OrderingFilter` is configured. It demonstrates ordering users within a specific group by the `created_at` field in descending order. ```graphql query { group(id: "xxx") { users(orderBy: "-created_at") { xxx } } } ``` -------------------------------- ### Test Graphene-Django GraphQL API with Django's test client Source: https://github.com/graphql-python/graphene-django/blob/main/README.md This example demonstrates how to write a test case for a Graphene-Django GraphQL API using `GraphQLTestCase`. It shows how to define the schema, execute a GraphQL query, and assert the response for errors and data content, ensuring the API functions as expected. ```python from django.test import TestCase from graphene_django.utils.testing import GraphQLTestCase from . import schema class MyModelAPITestCase(GraphQLTestCase): GRAPHENE_SCHEMA = schema.schema def test_query_all_mymodels(self): response = self.query( ''' query { mymodels { id name } } ''' ) self.assertResponseNoErrors(response) self.assertEqual(len(response.data['mymodels']), MyModel.objects.count()) ``` ```graphql query { mymodels { id name } } ``` -------------------------------- ### Partial Custom FilterSet Class Definition Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst An incomplete example showing the beginning of a custom `django_filters.FilterSet` class definition, typically used for more granular control over filtering behavior. ```python class AnimalFilter(django_filters.FilterSet): # Do case-insensitive lookups on 'name' ``` -------------------------------- ### Define Graphene Subscription Path Source: https://github.com/graphql-python/graphene-django/blob/main/docs/settings.rst Sets an alternative URL path for routing subscription operations, useful for advanced infrastructure setups (e.g., separate WSGI/ASGI servers). GraphiQL uses this for intelligent routing. Default: `None`. ```python GRAPHENE = { 'SUBSCRIPTION_PATH': "/ws/graphql" } ``` -------------------------------- ### Test GraphQL Queries and Mutations with unittest Source: https://github.com/graphql-python/graphene-django/blob/main/docs/testing.rst Demonstrates how to test GraphQL queries (basic and with variables) and mutations using `GraphQLTestCase` in Django's `unittest` framework. It includes examples of sending GraphQL operations and asserting for no errors in the response. ```python import json from graphene_django.utils.testing import GraphQLTestCase class MyFancyTestCase(GraphQLTestCase): def test_some_query(self): response = self.query( ''' query { myModel { id name } } ''', operation_name='myModel' ) content = json.loads(response.content) # This validates the status code and if you get errors self.assertResponseNoErrors(response) # Add some more asserts if you like ... def test_query_with_variables(self): response = self.query( ''' query myModel($id: Int!){ myModel(id: $id) { id name } } ''', operation_name='myModel', variables={'id': 1} ) content = json.loads(response.content) # This validates the status code and if you get errors self.assertResponseNoErrors(response) # Add some more asserts if you like ... def test_some_mutation(self): response = self.query( ''' mutation myMutation($input: MyMutationInput!) { myMutation(input: $input) { my-model { id name } } } ''', operation_name='myMutation', input_data={'my_field': 'foo', 'other_field': 'bar'} ) # This validates the status code and if you get errors self.assertResponseNoErrors(response) # Add some more asserts if you like ... ``` -------------------------------- ### Specify Fields for Automatic Choices to Enum Conversion Source: https://github.com/graphql-python/graphene-django/blob/main/docs/queries.rst This example shows how to explicitly list which fields should be converted to GraphQL enums by setting `convert_choices_to_enum` to a list of field names in the `Meta` class, allowing fine-grained control. ```python from graphene_django import DjangoObjectType from .models import PetModel class Pet(DjangoObjectType): class Meta: model = PetModel fields = ("id", "kind",) convert_choices_to_enum = ["kind"] ``` -------------------------------- ### Implement Graphene-Django Relay ClientIDMutation Source: https://github.com/graphql-python/graphene-django/blob/main/docs/mutations.rst Provides an example of a Graphene-Django Relay mutation, inheriting from `ClientIDMutation` and implementing the `mutate_and_get_payload` method. It shows how to define input arguments and handle global IDs for updating a model instance. ```python import graphene from graphene import relay from graphene_django import DjangoObjectType from graphql_relay import from_global_id from .queries import QuestionType class QuestionMutation(relay.ClientIDMutation): class Input: text = graphene.String(required=True) id = graphene.ID() question = graphene.Field(QuestionType) @classmethod def mutate_and_get_payload(cls, root, info, text, id): question = Question.objects.get(pk=from_global_id(id)[1]) question.text = text question.save() return QuestionMutation(question=question) ``` -------------------------------- ### Example GraphQL Query for Relay Connection Pagination Source: https://github.com/graphql-python/graphene-django/blob/main/docs/queries.rst This GraphQL query demonstrates fetching paginated data using Relay's connection specification. It utilizes `first` and `after` arguments for slicing, and requests `pageInfo` (start/end cursors, hasNext/PreviousPage) and `edges` (cursor, node ID, question_text) for each item. ```graphql { questions (first: 2, after: "YXJyYXljb25uZWN0aW9uOjEwNQ==") { pageInfo { startCursor endCursor hasNextPage hasPreviousPage } edges { cursor node { id question_text } } } } ``` -------------------------------- ### Test GraphQL Queries with pytest Source: https://github.com/graphql-python/graphene-django/blob/main/docs/testing.rst Demonstrates how to set up a `pytest` fixture using the `graphql_query` helper and `pytest-django`'s `client` fixture to facilitate testing GraphQL queries. It includes an example of a test function asserting no errors in the GraphQL response. ```python # Create a fixture using the graphql_query helper and `client` fixture from `pytest-django`. import json import pytest from graphene_django.utils.testing import graphql_query @pytest.fixture def client_query(client): def func(*args, **kwargs): return graphql_query(*args, **kwargs, client=client) return func # Test you query using the client_query fixture def test_some_query(client_query): response = client_query( ''' query { myModel { id name } } ''', operation_name='myModel' ) content = json.loads(response.content) assert 'errors' not in content ``` -------------------------------- ### Add Custom Fields and Resolvers to DjangoObjectType Source: https://github.com/graphql-python/graphene-django/blob/main/docs/queries.rst This example shows how to extend a `DjangoObjectType` by adding a new custom field (`extra_field`) and defining a resolver method (`resolve_extra_field`) for it, allowing for computed or non-model-backed fields. ```python from graphene_django import DjangoObjectType from .models import Question class QuestionType(DjangoObjectType): class Meta: model = Question fields = ("id", "question_text") extra_field = graphene.String() def resolve_extra_field(self, info): return "hello!" ``` -------------------------------- ### Define Graphene-Django Query and ObjectType for a Django Model Source: https://github.com/graphql-python/graphene-django/blob/main/docs/queries.rst This comprehensive example demonstrates how to create a `DjangoObjectType` from a Django `Question` model and define a `Query` class with methods to resolve lists and single instances of `Question` objects, showcasing basic GraphQL query capabilities. ```python # my_app/schema.py import graphene from graphene_django import DjangoObjectType from .models import Question class QuestionType(DjangoObjectType): class Meta: model = Question fields = ("id", "question_text") class Query(graphene.ObjectType): questions = graphene.List(QuestionType) question_by_id = graphene.Field(QuestionType, id=graphene.String()) def resolve_questions(root, info, **kwargs): # Querying a list return Question.objects.all() def resolve_question_by_id(root, info, id): # Querying a single question return Question.objects.get(pk=id) ``` -------------------------------- ### Query GraphQL Debug Information Source: https://github.com/graphql-python/graphene-django/blob/main/docs/debug.rst This GraphQL query example shows how to retrieve debugging information, including raw SQL queries and exceptions, by querying the `_debug` field. It demonstrates a typical GraphQL query structure alongside the debug field, which must be the last field in the query. ```graphql { # A example that will use the ORM for interact with the DB allIngredients { edges { node { id, name } } } # Here is the debug field that will output the SQL queries _debug { sql { rawSql } exceptions { message stack } } } ``` -------------------------------- ### Initial Django FilterSet and Graphene-Django Type Definitions Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst This snippet demonstrates the basic setup for integrating `django-filters` with `graphene-django`. It defines a `FilterSet` for an `Animal` model, a `DjangoObjectType` for the GraphQL schema, and a `Query` class to expose `Animal` data with filtering capabilities via `DjangoFilterConnectionField`. ```python name = django_filters.CharFilter(lookup_expr=['iexact']) class Meta: # Assume you have an Animal model defined with the following fields model = Animal fields = ['name', 'genus', 'is_domesticated'] class AnimalNode(DjangoObjectType): class Meta: model = Animal fields = '__all__' filterset_class = AnimalFilter interfaces = (relay.Node, ) class Query(ObjectType): animal = relay.Node.Field(AnimalNode) all_animals = DjangoFilterConnectionField(AnimalNode) ``` -------------------------------- ### Example JSON Response for GraphQL Relay Connection Query Source: https://github.com/graphql-python/graphene-django/blob/main/docs/queries.rst This JSON object illustrates the expected response format for a GraphQL Relay connection query. It includes the `pageInfo` object with pagination metadata and an `edges` array, where each edge contains a `cursor` and the `node` data (ID, question_text). ```json { "data": { "questions": { "pageInfo": { "startCursor": "YXJyYXljb25uZWN0aW9uOjEwNg==", "endCursor": "YXJyYXljb25uZWN0aW9uOjEwNw==", "hasNextPage": true, "hasPreviousPage": false }, "edges": [ { "cursor": "YXJyYXljb25uZWN0aW9uOjEwNg==", "node": { "id": "UGxhY2VUeXBlOjEwNw==", "question_text": "How did we get here?" } }, { "cursor": "YXJyYXljb25uZWN0aW9uOjEwNw==", "node": { "id": "UGxhY2VUeXBlOjEwOA==", "name": "Where are we?" } } ] } } } ``` -------------------------------- ### Extend Graphene Schema with external Query and Mutation types in Python Source: https://github.com/graphql-python/graphene-django/blob/main/docs/schema.rst This example illustrates how to extend an existing `graphene.Schema` by incorporating custom `Query` and `Mutation` objects from other modules (e.g., `my_app.schema`). It shows how to use mixins to combine multiple `ObjectType` definitions into the main schema. ```python import graphene import my_app.schema.Query import my_app.schema.Mutation class Query( my_app.schema.Query, # Add your Query objects here graphene.ObjectType ): pass class Mutation( my_app.schema.Mutation, # Add your Mutation objects here graphene.ObjectType ): pass schema = graphene.Schema(query=Query, mutation=Mutation) ``` -------------------------------- ### Creating a GraphQL Mutation from a Django Form Source: https://github.com/graphql-python/graphene-django/blob/main/docs/mutations.rst This example illustrates the use of `DjangoFormMutation` to automatically generate a GraphQL mutation from a standard Django form. It defines a simple `forms.Form` and then creates a `DjangoFormMutation` subclass, linking it via the `Meta.form_class` attribute. This simplifies the process of exposing form-based inputs in GraphQL. ```python from graphene_django.forms.mutation import DjangoFormMutation class MyForm(forms.Form): name = forms.CharField() class MyMutation(DjangoFormMutation): class Meta: form_class = MyForm ``` -------------------------------- ### Define Basic Filterable Fields for DjangoObjectType Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst Demonstrates how to specify simple `filter_fields` in a `DjangoObjectType`'s `Meta` class to enable basic filtering on model fields like `name`, `genus`, and `is_domesticated`. Includes a GraphQL query example for filtering by `genus` and `isDomesticated`. ```python class AnimalNode(DjangoObjectType): class Meta: # Assume you have an Animal model defined with the following fields model = Animal fields = '__all__' filter_fields = ['name', 'genus', 'is_domesticated'] interfaces = (relay.Node, ) ``` ```graphql query { # Note that fields names become camelcased allAnimals(genus: "cat", isDomesticated: true) { edges { node { id, name } } } } ``` -------------------------------- ### Perform Initial Django Database Migration Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This bash command navigates back to the project root and runs the initial Django database migration, which sets up the necessary default tables for the project's database. ```bash cd .. python manage.py migrate ``` -------------------------------- ### Implement Custom django-filter FilterSet for Advanced Filtering Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst Illustrates how to create a custom `django_filters.FilterSet` class to define advanced filtering logic, such as case-insensitive lookups or multiple-choice selections. This custom filterset is then applied to a `DjangoFilterConnectionField` in the Graphene `Query` class. Includes a GraphQL query example using the custom filter. ```python class AnimalNode(DjangoObjectType): class Meta: # Assume you have an Animal model defined with the following fields model = Animal fields = '__all__' filter_fields = ['name', 'genus', 'is_domesticated'] interfaces = (relay.Node, ) class AnimalFilter(django_filters.FilterSet): # Do case-insensitive lookups on 'name' name = django_filters.CharFilter(lookup_expr=['iexact']) # Allow multiple genera to be selected at once genera = django_filters.MultipleChoiceFilter( field_name='genus', choices=( ('Canis', 'Canis'), ('Panthera', 'Panthera'), ('Seahorse', 'Seahorse') ) ) class Meta: model = Animal fields = ['name', 'genus', 'is_domesticated'] class Query(ObjectType): animal = relay.Node.Field(AnimalNode) # We specify our custom AnimalFilter using the filterset_class param all_animals = DjangoFilterConnectionField(AnimalNode, filterset_class=AnimalFilter) ``` ```graphql query { allAnimals(genera: ["Canis", "Panthera"]) { edges { node { id, name } } } } ``` -------------------------------- ### Customizing Input and Return Field Names in DjangoModelFormMutation Source: https://github.com/graphql-python/graphene-django/blob/main/docs/mutations.rst This example shows how to customize the default input and return field names for a `DjangoModelFormMutation`. By setting `input_field_name` and `return_field_name` in the `Meta` class, developers can control how the mutation's arguments are named and what the successful response field is called in the GraphQL schema. ```python class PetMutation(DjangoModelFormMutation): class Meta: form_class = PetForm input_field_name = 'data' return_field_name = 'my_pet' ``` -------------------------------- ### Run Initial Django Database Migrations Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Command to apply initial database migrations for the newly created Django project and its applications. ```bash python manage.py migrate ``` -------------------------------- ### Run Django Development Server Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Bash command initiates the Django development server, making the web application and its GraphQL API accessible locally. It's a standard command for testing Django projects during development. ```bash python manage.py runserver ``` -------------------------------- ### Add Graphene-Django to Django INSTALLED_APPS Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This configuration snippet for Django's `settings.py` demonstrates how to enable the `graphene_django` application. Adding it to `INSTALLED_APPS` is a prerequisite for integrating Graphene's GraphQL functionalities into a Django project. ```python # cookbook/settings.py INSTALLED_APPS = [ ... "graphene_django", ] ``` -------------------------------- ### Add Ingredients App to Django Settings Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python snippet demonstrates how to register the newly created `ingredients` app in the `INSTALLED_APPS` list within the Django project's `settings.py` file. This step is crucial for Django to discover and include the app's models and configurations. ```python # cookbook/settings.py INSTALLED_APPS = [ ... # Install the ingredients app "cookbook.ingredients", ] ``` -------------------------------- ### Add Graphene-Django and App to INSTALLED_APPS Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Configures Django's `INSTALLED_APPS` to include `graphene_django` and the `ingredients` app, making necessary commands and functionalities available. ```python INSTALLED_APPS = [ ... # This will also make the `graphql_schema` management command available 'graphene_django', # Install the ingredients app 'ingredients', ] ``` -------------------------------- ### Load Test Data from Fixture Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This bash command loads sample data into the Django database from a specified JSON fixture file named `ingredients`. This is a convenient way to populate the database with initial or test data without manual entry. ```bash python manage.py loaddata ingredients ``` -------------------------------- ### Create and Apply Django Model Migrations Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Commands to generate new database migrations based on changes to Django models and then apply those migrations to the database. ```bash python manage.py makemigrations python manage.py migrate ``` -------------------------------- ### Query All Ingredients Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst A GraphQL query to retrieve the `id` and `name` of all ingredients available in the system, demonstrating basic data fetching. ```graphql query { allIngredients { edges { node { id, name } } } } ``` -------------------------------- ### GraphQL Query for All Ingredients Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This GraphQL query fetches all available ingredients from the API. It requests the `id` and `name` fields for each ingredient, demonstrating a basic data retrieval operation. ```graphql query { allIngredients { id name } } ``` -------------------------------- ### Create GraphQL and GraphiQL URL Endpoint Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Defines a URL pattern for the GraphQL endpoint using `GraphQLView.as_view()`, enabling the GraphiQL IDE for interactive testing. ```python from django.conf.urls import url, include from django.contrib import admin from graphene_django.views import GraphQLView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^graphql$', GraphQLView.as_as_view(graphiql=True)), ] ``` -------------------------------- ### Example GraphQL Query for ArrayField Filtering Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst This GraphQL query demonstrates how to filter events based on values within a PostgreSQL `ArrayField`. It uses the `tags_Overlap` argument to retrieve events that have any of the specified tags ('concert', 'festival'). ```graphql query { events(tags_Overlap: ["concert", "festival"]) { name } } ``` -------------------------------- ### Load Test Data into Django Database Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Command to load fixture data from a JSON file into the Django database, populating models with initial test entries. ```bash $ python ./manage.py loaddata ingredients ``` -------------------------------- ### Configure Django URLs for GraphQL and GraphiQL Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python code for `urls.py` sets up a single GraphQL endpoint at `/graphql` using Graphene's `GraphQLView`. It also enables the GraphiQL interface for interactive query testing and applies `csrf_exempt` for convenience in development. ```python # cookbook/urls.py from django.contrib import admin from django.urls import path from django.views.decorators.csrf import csrf_exempt from graphene_django.views import GraphQLView urlpatterns = [ path("admin/", admin.site.urls), path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True))), ] ``` -------------------------------- ### Generate and Apply Django Migrations Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst These bash commands are used to manage database schema changes. `makemigrations` creates new migration files based on changes detected in the models, and `migrate` applies those pending migrations to update the database schema. ```bash python manage.py makemigrations python manage.py migrate ``` -------------------------------- ### Define Project-Level Graphene Schema Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Creates the main Graphene schema for the project by combining app-level queries, allowing for a unified GraphQL endpoint. ```python import graphene import ingredients.schema class Query(ingredients.schema.Query, graphene.ObjectType): # This class will inherit from multiple Queries # as we begin to add more apps to our project pass schema = graphene.Schema(query=Query) ``` -------------------------------- ### Implement custom resolvers for DjangoListField Source: https://github.com/graphql-python/graphene-django/blob/main/docs/fields.rst This example illustrates how to apply custom filtering to DjangoListField results using both the DjangoObjectType's get_queryset method and the Query object's field resolver. It demonstrates filtering for published recipes and those with a title. ```python from graphene import ObjectType, Schema from graphene_django import DjangoListField class RecipeType(DjangoObjectType): class Meta: model = Recipe fields = ("title", "instructions") @classmethod def get_queryset(cls, queryset, info): # Filter out recipes that have no title return queryset.exclude(title__exact="") class Query(ObjectType): recipes = DjangoListField(RecipeType) def resolve_recipes(parent, info): # Only get recipes that have been published return Recipe.objects.filter(published=True) schema = Schema(query=Query) ``` -------------------------------- ### Filter Queryset for List Fields in Graphene Source: https://github.com/graphql-python/graphene-django/blob/main/docs/authorization.rst This example shows how to filter a queryset for a list field (`all_posts`) in a Graphene `Query` object. By defining a `resolve_all_posts` method, the returned queryset can be restricted, in this case, to only include `Post` objects where `published` is `True`. ```python from graphene import ObjectType from graphene_django.filter import DjangoFilterConnectionField from .models import Post class Query(ObjectType): all_posts = DjangoFilterConnectionField(PostNode) def resolve_all_posts(self, info): return Post.objects.filter(published=True) ``` -------------------------------- ### Example GraphQL Mutation with Multiple Atomic Operations Source: https://github.com/graphql-python/graphene-django/blob/main/docs/mutations.rst A GraphQL mutation demonstrating two `increaseCredits` operations. When `ATOMIC_MUTATIONS` is enabled, if one operation fails (e.g., invalid amount), the entire transaction is rolled back, ensuring no partial updates occur. ```graphql mutation IncreaseCreditsTwice { increaseCredits1: increaseCredits(input: { amount: 10 }) { balance errors { field messages } } increaseCredits2: increaseCredits(input: { amount: -1 }) { balance errors { field messages } } } ``` -------------------------------- ### Run Graphene-Django Test Suite Source: https://github.com/graphql-python/graphene-django/blob/main/CONTRIBUTING.md Executes the full test suite for the graphene-django project to verify functionality and ensure code changes haven't introduced regressions. ```sh make tests ``` -------------------------------- ### Implement Context-Dependent Filtering with Request Object Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst This example shows how to customize a `django_filters.FilterSet` to perform context-dependent filtering. By overriding the `qs` property, it accesses the `request` object (passed as `context`) to filter results based on the authenticated user, allowing for personalized data retrieval. ```python class AnimalFilter(django_filters.FilterSet): # Do case-insensitive lookups on 'name' name = django_filters.CharFilter(lookup_type=['iexact']) class Meta: model = Animal fields = ['name', 'genus', 'is_domesticated'] @property def qs(self): # The query context can be found in self.request. return super(AnimalFilter, self).qs.filter(owner=self.request.user) ``` -------------------------------- ### Configure Graphene Schema in Django Settings Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Specifies the path to the main Graphene schema within Django's settings, allowing Graphene to locate and use it for the GraphQL endpoint. ```python GRAPHENE = { 'SCHEMA': 'cookbook.schema.schema' } ``` -------------------------------- ### Define Complex Lookup Types for DjangoObjectType Filtering Source: https://github.com/graphql-python/graphene-django/blob/main/docs/filtering.rst Shows how to configure `filter_fields` with a dictionary to allow more complex lookup types (e.g., `exact`, `icontains`, `istartswith`) for specific fields in a `DjangoObjectType`. Includes a GraphQL query example demonstrating a case-insensitive contains lookup. ```python class AnimalNode(DjangoObjectType): class Meta: model = Animal fields = '__all__' # Provide more complex lookup types filter_fields = { 'name': ['exact', 'icontains', 'istartswith'], 'genus': ['exact'], 'is_domesticated': ['exact'], } interfaces = (relay.Node, ) ``` ```graphql query { # Note that fields names become camelcased allAnimals(name_Icontains: "lion") { edges { node { id, name } } } } ``` -------------------------------- ### Define Django Models for Ingredients Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python code defines two Django models, `Category` and `Ingredient`, within the `cookbook/ingredients/models.py` file. It establishes a `ForeignKey` relationship, linking ingredients to categories, and includes `__str__` methods for human-readable representation. ```python # cookbook/ingredients/models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() category = models.ForeignKey( Category, related_name="ingredients", on_delete=models.CASCADE ) def __str__(self): return self.name ``` -------------------------------- ### Create GraphQL and GraphiQL URL Endpoint with Explicit Schema Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst An alternative method to define the GraphQL endpoint, explicitly passing the Graphene schema to `GraphQLView.as_view()` directly in the URL configuration. ```python from django.conf.urls import url, include from django.contrib import admin from graphene_django.views import GraphQLView from cookbook.schema import schema urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^graphql$', GraphQLView.as_view(graphiql=True, schema=schema)), ] ``` -------------------------------- ### Define Graphene Schema and Object Types Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python code, located in `cookbook/schema.py`, defines the GraphQL schema using Graphene. It creates `DjangoObjectType` classes for `Category` and `Ingredient` models, automatically mapping their fields, and then defines a `Query` class to expose `all_ingredients` as a list of `IngredientType`. ```python # cookbook/schema.py import graphene from graphene_django import DjangoObjectType from cookbook.ingredients.models import Category, Ingredient class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id", "name", "ingredients") class IngredientType(DjangoObjectType): class Meta: model = Ingredient fields = ("id", "name", "notes", "category") class Query(graphene.ObjectType): all_ingredients = graphene.List(IngredientType) ``` -------------------------------- ### Configure Graphene-Django in Django settings Source: https://github.com/graphql-python/graphene-django/blob/main/README.md This Python snippet shows how to configure Graphene-Django in a Django project's `settings.py` file. It involves adding 'graphene_django' to the `INSTALLED_APPS` list and defining the GraphQL schema's path within the `GRAPHENE` dictionary. ```python INSTALLED_APPS = [ # ... 'graphene_django', ] GRAPHENE = { 'SCHEMA': 'myapp.schema.schema' } ``` -------------------------------- ### Python Project Dependencies Source: https://github.com/graphql-python/graphene-django/blob/main/examples/cookbook-plain/requirements.txt This snippet lists the essential Python packages and their version constraints, typically found in a `requirements.txt` file. It ensures that the project runs with compatible versions of `django`, `graphene`, and `graphene-django`, preventing potential conflicts and ensuring consistent behavior across environments. ```Python django~=3.2 graphene graphene-django>=3.1 ``` -------------------------------- ### Define Graphene-Django GraphQL Schema and Resolvers Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python snippet defines parts of a Graphene `Query` type, including a field `category_by_name` and resolver methods `resolve_all_ingredients` and `resolve_category_by_name`. It also initializes the main Graphene schema, demonstrating how to expose Django model data through a GraphQL API. ```python category_by_name = graphene.Field(CategoryType, name=graphene.String(required=True)) def resolve_all_ingredients(root, info): # We can easily optimize query count in the resolve method return Ingredient.objects.select_related("category").all() def resolve_category_by_name(root, info, name): try: return Category.objects.get(name=name) except Category.DoesNotExist: return None schema = graphene.Schema(query=Query) ``` -------------------------------- ### JSON Response for Failed Atomic GraphQL Mutation Source: https://github.com/graphql-python/graphene-django/blob/main/docs/mutations.rst The expected JSON response for the example GraphQL mutation where the second `increaseCredits` operation fails due to an invalid amount. Despite the partial success indicated in the response, the `ATOMIC_MUTATIONS` setting ensures the database balance remains unchanged. ```json { "data": { "increaseCredits1": { "balance": 10.0, "errors": [] }, "increaseCredits2": { "balance": null, "errors": [ { "field": "amount", "message": "Amount should be a positive number" } ] } } } ``` -------------------------------- ### Configure Ingredients App in apps.py Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python code defines the `AppConfig` for the `ingredients` app in `cookbook/ingredients/apps.py`. It specifies the `default_auto_field` for primary keys and explicitly sets the `name` of the app, which is important for Django's internal app registry. ```python # cookbook/ingredients/apps.py from django.apps import AppConfig class IngredientsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'cookbook.ingredients' ``` -------------------------------- ### Configure Graphene Schema in Django Settings Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python snippet for `settings.py` shows how to specify the path to the main Graphene schema object. This configuration allows Graphene-Django to automatically locate and use the defined GraphQL schema for handling API requests. ```python # cookbook/settings.py GRAPHENE = { "SCHEMA": "cookbook.schema.schema" } ``` -------------------------------- ### Configure Graphene-Django Settings Dictionary Source: https://github.com/graphql-python/graphene-django/blob/main/docs/settings.rst Add settings to your Django project by creating a Dictionary named `GRAPHENE` in the project's `settings.py` file. ```python GRAPHENE = { ... } ``` -------------------------------- ### Query All Categories with Nested Ingredients Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst A GraphQL query that retrieves all categories and, for each category, lists the names of its associated ingredients, demonstrating nested queries. ```graphql query { allCategories { edges { node { name, ingredients { edges { node { name } } } } } } } ``` -------------------------------- ### Expose Graphene-Django GraphQL API in Django URLs Source: https://github.com/graphql-python/graphene-django/blob/main/README.md This Python snippet shows how to integrate the Graphene-Django GraphQL API into a Django project's `urls.py`. It maps the `/graphql/` endpoint to `GraphQLView.as_view(graphiql=True)`, which enables the GraphiQL in-browser IDE for testing and exploring the API. ```python from django.urls import path from graphene_django.views import GraphQLView from . import schema urlpatterns = [ # ... path('graphql/', GraphQLView.as_view(graphiql=True)), # Given that schema path is defined in GRAPHENE['SCHEMA'] in your settings.py ] ``` -------------------------------- ### Export GraphQL Schema as SDL File Source: https://github.com/graphql-python/graphene-django/blob/main/docs/introspection.rst This bash command exports the Graphene schema (`tutorial.quickstart.schema`) as a GraphQL Schema Definition Language (SDL) file named `schema.graphql`. This provides a human-readable and portable representation of your GraphQL schema. ```bash ./manage.py graphql_schema --schema tutorial.quickstart.schema --out schema.graphql ``` -------------------------------- ### Query All Ingredients with Category Details Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This GraphQL query retrieves a list of all ingredients. For each ingredient, it fetches its unique identifier (id), name, and details about its associated category, including the category's id and name. ```GraphQL query { allIngredients { id name category { id name } } } ``` -------------------------------- ### Format and Lint Graphene-Django Code Locally Source: https://github.com/graphql-python/graphene-django/blob/main/CONTRIBUTING.md Applies code formatting and runs lint checks locally to ensure code quality and adherence to project standards before submitting a pull request, which helps save time on CI checks. ```sh make format make lint ``` -------------------------------- ### Define Graphene Query Object with Simple Resolver Source: https://github.com/graphql-python/graphene-django/blob/main/docs/queries.rst Illustrates how to define a `graphene.ObjectType` as a root `Query` and implement a basic resolver (`resolve_foo`) to fetch data, demonstrating the connection between a GraphQL field and its data source. ```python import graphene from .models import Question from .types import QuestionType class Query(graphene.ObjectType): foo = graphene.List(QuestionType) def resolve_foo(root, info, **kwargs): id = kwargs.get("id") return Question.objects.get(id) ``` -------------------------------- ### Register Models with Django Admin Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-plain.rst This Python code, placed in `cookbook/ingredients/admin.py`, registers the `Category` and `Ingredient` models with the Django administration site. This allows administrators to view, add, edit, and delete instances of these models through the built-in Django admin interface. ```python # cookbook/ingredients/admin.py from django.contrib import admin from cookbook.ingredients.models import Category, Ingredient admin.site.register(Category) admin.site.register(Ingredient) ``` -------------------------------- ### Initialize a basic Graphene Schema in Python Source: https://github.com/graphql-python/graphene-django/blob/main/docs/schema.rst This snippet demonstrates the most basic way to create a `graphene.Schema` object in Python, defining empty `Query` and `Mutation` types that can be extended later. It sets up the fundamental structure for a GraphQL API. ```python import graphene class Query(graphene.ObjectType): pass class Mutation(graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) ``` -------------------------------- ### Define Django Models for Ingredients App Source: https://github.com/graphql-python/graphene-django/blob/main/docs/tutorial-relay.rst Python code defining `Category` and `Ingredient` models using Django's ORM, including fields like name, notes, and a foreign key relationship. ```python # cookbook/ingredients/models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() category = models.ForeignKey(Category, related_name='ingredients', on_delete=models.CASCADE) def __str__(self): return self.name ``` -------------------------------- ### Define GraphQL types and queries with Graphene-Django Source: https://github.com/graphql-python/graphene-django/blob/main/README.md This Python code demonstrates how to create a `schema.py` file in a Django app. It defines a `DjangoObjectType` for a Django model (`MyModel`) and a `Query` class to expose model data via GraphQL, including a resolver function to fetch all instances of the model. ```python import graphene from graphene_django import DjangoObjectType from .models import MyModel class MyModelType(DjangoObjectType): class Meta: model = MyModel class Query(graphene.ObjectType): mymodels = graphene.List(MyModelType) def resolve_mymodels(self, info, **kwargs): return MyModel.objects.all() schema = graphene.Schema(query=Query) ```