#django #graphql #django-urls #graphene-django
Вопрос:
Я новичок в django и GraphQL. Я работаю с 2 базами данных, которые имеют точно такую же схему. Проблема в том, что мой запрос и мутации выполняются только в одной базе данных.
Я пытаюсь закодировать серверную часть, где:
- Моя новостная статья (идентификатор,полное описание) находится в базе данных TestDb. Итак, мне нужно мутировать и запрашивать базу данных тестов.
- Я обрабатываю их (преобразование в нижний регистр удаление знаков препинания) и сохраняю в OutDb. Аналогично, мне нужно мутировать и запрашивать OutDb.
- Я правильно настроил операции с 2 базами данных, используя маршрутизаторы баз данных.
Мое приложение-драйвер NewsArticle
, и я реализовал 2 приложения Django для обработки 2 бд test_read_db
и test_read_db
## `test_read_db/models.py`##
------------
from djongo import models
# Create your models here.
class TestDb(models.Model):
_id = models.CharField(max_length=300, primary_key=True)
FullDescription = models.TextField(blank=False)
class Meta:
db_table = 'input_triples_collection'
indexes = [models.Index(fields=['_id', 'FullDescription']),]
И
## `test_write_db/models.py`##
------------
from djongo import models
# Create your models here.
class OutDb(models.Model):
_id = models.CharField(max_length=300, primary_key=True)
FullDescription = models.TextField(blank=False)
class Meta:
db_table = 'output_triples_collection'
indexes = [models.Index(fields=['_id', 'FullDescription']),]
Как видно, схема для обеих баз данных абсолютно одинакова.
Я определил отдельные типы GrahpQL, запросы, мутации для обоих приложений. Например, запросы выглядят так:
## `test_read_db/queries.py`##
------------
import graphene
from test_read_db.types import FullDescriptionTestDbType
from test_read_db.models import TestDb
class Query(graphene.ObjectType):
description = graphene.List(FullDescriptionTestDbType)
def resolve_description(root, info, **kwargs):
# Querying a list
return TestDb.objects.all()
## `test_write_db/queries.py`##
------------
import graphene
from test_write_db.types import FullDescriptionOutDbType
from test_write_db.models import OutDb
class Query(graphene.ObjectType):
description = graphene.List(FullDescriptionOutDbType)
def resolve_description(root, info, **kwargs):
# Querying a list
return OutDb.objects.all()
And, I tied URLs togather in my main app
## `NewsArticle/schema.py`##
------------
import graphene
import test_read_db.queries as test_read_query
import test_read_db.mutations as test_read_mutation
import test_write_db.queries as test_write_query
import test_write_db.mutations as test_write_mutation
class Query(test_read_query.Query, test_write_query.Query, graphene.ObjectType):
pass
class Mutation(test_read_mutation.Mutation, test_write_mutation.Mutation, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query, mutation=Mutation)
## `NewsArticle/urls.py`##
------------
from django.contrib import admin
from django.urls import path
from graphene_django.views import GraphQLView
from NewsArticle.schema import schema
urlpatterns = [
path('admin/', admin.site.urls),
path('graphql', GraphQLView.as_view(graphiql=True, schema=schema)),
]
- Now, when I try to add read from / write to using graphiQL, only TestDb data is altered.
Example:
query{
description{
Id,
FullDescription
}
}
returns content of TestDb, but does not return content of OutDb
{
"data": {
"description": [
{
"Id": "test1234",
"FullDescription": "test"
}
]
}
}
Similarly, mutations alter only TestDb, whereas I expected that both TestDb and OutDb shall get written
mutation {
createDescription(input: {FullDescription: "test", Id: "test123"}) {
fullDescription {
Id
FullDescription
}
}
}
Writes following only to TestDB
{
"data": {
"createDescription": {
"fullDescription": {
"Id": "test123",
"FullDescription": "test"
}
}
}
}
- How to tackle this situation? How should I restructure my apps? Do i need some to implement some logic to Choose Query belonging to particular app in NewsArticle/schema.py?