SoFunction
Updated on 2025-03-02

Django using graphql instance

1. Development environment

1、python3.6

2、django2.0

3、window10

2. Project construction

1. Create a virtual space mkvirtualenv space name

2. Create a django project

3. Install graphql's dependency package

pip install graphene-django

4. Create a component blog

5. Inject component blog and graphene_django into the app

6. Configure mysql database connection in

3. Write the content of the blog

1. Write the data model in

from  import models

# Create your models here.
class User():
 name = (max_length=100, verbose_name="Blogger's Name")
 gender = (max_length=6, choices=(('male', u'male'), ('female', 'female')), default='female',
        verbose_name='gender')
 create_at = (auto_now_add=True, verbose_name='Create time')

class Blog():
 title = (max_length=100, verbose_name='title')
 user = (User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='Blogger')
 content = (verbose_name='Blog content')
 create_at = (auto_now_add=True, verbose_name='Create time')
 update_at = (auto_now=True, verbose_name='Update time')

2. Create a new file

#!/usr/bin/env python
# encoding: utf-8

import graphene
from graphene_django.types import DjangoObjectType
from .models import User, Blog

class UserType(DjangoObjectType):
 class Meta:
  model = User

class BlogType(DjangoObjectType):
 class Meta:
  model = Blog

# Define action rating input typeclass UserInput():
 name = (required=True)
 gender = (required=True)

class BlogInput():
 title = (required=True)
 user = (required=True)
 content = (required=True)

# Define a mutation to create a userclass CreateUser():
 #Api input parameters class Arguments:
  user_data = UserInput(required=True)

 #api response parameters ok = ()
 user = (UserType)

 #Api's corresponding operation, here is create def mutate(self, info, user_data):
  user = (name=user_data['name'], gender=user_data['gender'])
  ok = True
  return CreateUser(user=user, ok=ok)


# Define a mutation to create a blogclass CreateBlog():
 class Arguments:
  blog_data = BlogInput(required=True)

 blog = (BlogType)

 def mutate(self, info, blog_data):
  # Insert into the database  blog = (title=blog_data['title'], user_id=blog_data['user'], content=blog_data['content'])
  return CreateBlog(blog=blog)

# Define a query statementclass Query(object):
 all_user = (UserType)
 all_blog = (BlogType)

 def resolve_all_user(self, info, **kwargs):
  # Query the logic of all books  return ()

 def resolve_all_blog(self, info, **kwargs):
  # Query the logic of all titles  return ()

3. Create a total project in the directory (and the same level)

import graphene
import , 

class Query(, ):
 # The query portal of the total Schema pass

class Mutations():
 # Total schema mutations entrance create_user = ()
 create_blog = ()

schema = (query=Query, mutation=Mutations)

4. Configure the URL

from  import admin
from  import path
from graphene_django.views import GraphQLView
from .schema import schema
urlpatterns = [
 path('admin/', ),
 path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)),
]

5. Generate database mapping and start project, access directly on the browser

4. You can adjust the above code

1. Define Mutations separately in their respective

# Define a total mutation exitclass Mutation():
 create_user = ()
 create_blog = ()

2. Introduce operations like type Query in the overall

class Mutations(, ):
 # Total schema mutations entrance pass

3. The input data type can be directly defined in the mutation

class CreateUser():
 #Api input parameters (class name can be defined at will) class Arguments:
  name = (required=True)
  gender = (required=True)

 #api response parameters ok = ()
 user = (UserType)

 #Api's corresponding operation, here is create def mutate(self, info, name, gender):
  user = (name=name, gender=gender)
  ok = True
  return CreateUser(user=user, ok=ok)

5. Use conditional query in Query statements

1. App's schema (official plan example)

import graphene
from graphene_django.types import DjangoObjectType
from .models import Category, Ingredient

class CategoryType(DjangoObjectType):
 class Meta:
  model = Category

class IngredientType(DjangoObjectType):
 class Meta:
  model = Ingredient

# Define a queryclass Query(object):
 # Define a query based on id or name category = (CategoryType,
        id=(),
        name=())
 # Query all all_categories = (CategoryType)
 # Query according to the conditions ingredient = (IngredientType,
        id=(),
        name=())
 # Query all all_ingredients = (IngredientType)

 def resolve_all_categories(self, info, **kwargs):
  return ()

 def resolve_all_ingredients(self, info, **kwargs):
  # We can easily optimize query count in the resolve method
  return .select_related('category').all()

 # Define query statements def resolve_category(self, info, **kwargs):
  id = ('id')
  name = ('name')

  if id is not None:
   return (pk=id)

  if name is not None:
   return (name=name)

  return None

 def resolve_ingredient(self, info, **kwargs):
  id = ('id')
  name = ('name')

  if id is not None:
   return (pk=id)

  if name is not None:
   return (name=name)

  return None

Official website address

Supplementary knowledge:Record several ways to use timers in python

Method 1: Directly use the while loop

from datetime import datetime
import time

# Execute once every n secondsdef timer(n):
  while True:
    print(().strftime("%Y-%m-%d %H:%M:%S"))
    (n)

timer(5)

Method 2: Use Timer in threading module

from datetime import datetime
from threading import Timer

# Print time functiondef print_time(inc):
  print(().strftime("%Y-%m-%d %H:%M:%S"))
  """
  TimerParameter description
  inc:Indicates the time interval
  print_time:Executed functions
  (inc,):Parameters passed to the execution function
  """
  t = Timer(inc, print_time, (inc,))
  ()

print_time(2)

Method 3: Use the sched module

import time
import sched
from datetime import datetime

# Initialize the scheduler class of the sched module# The first parameter is a function that can return a timestamp, and the second parameter can be blocked before the timing reaches the time.schedule = (, )

# Function triggered by periodic schedulingdef print_time(inc):
  print(().strftime("%Y-%m-%d %H:%M:%S"))
  (inc, 0, print_time, (inc,))

# Default parameter 60 sdef start(inc=60):
  # Enter four parameters are: interval events, priority (used to sequence when two events that arrive at the same time are executed at the same time), the function triggered by the call, and the parameters to the triggered function (tuple form)  (0, 0, print_time, (inc,))
  ()

if __name__ == "__main__":
  start(10)

Method 4: Use apscheduler

from  import BlockingScheduler
from datetime import datetime


def job():
  print(().strftime('%Y-%m-%d %H:%M:%S'))


if __name__ == "__main__":
  scheduler = BlockingScheduler()
  scheduler.add_job(job, 'interval', seconds=5)
  ()

The above example of using graphql in django is all the content I share with you. I hope you can give you a reference and I hope you can support me more.