question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Return schema from query database

See original GitHub issue

Hi! I recently discover this package and I’m in love with it, it is an awesome work you done, all of you.

But, I want to return an Schema from the result of a query to the ddbb, and I don’t get it how it can be done, Can you please leave me a hint or a hand?

schemas.py

class TicketHistorySchemaOut(Schema):
    purchase_id: int
    offer_name: str
    price: int
    offer_duration: int

api.py

class GlobalAuth(HttpBearer):
    def authenticate(self, request, token):
        env_tk = env.str('API_TOKEN', default='rAIGCokgCIKBXNeWwYVzGFbEqTwFMsQG')
        if token == env_tk:
            return token

        with connection.cursor() as cursor:
            cursor.execute(f"SELECT `key` FROM authtoken_token WHERE `key` = '{token}'")
            result = cursor.fetchone()
            if result is not None:
                return token

api = NinjaAPI(
    version="1.0.0",
    auth=GlobalAuth()
)

@api.get('/consumption/ticket-services/history/{language}/{payment_object_id}/')
def get_history(request, language: str, payment_object_id: int):
    with connection.cursor() as cursor:
        query = f"""
            SELECT
                op.purchase_id,
                CASE WHEN ol.name IS NULL
                THEN o.name
                ELSE ol.name END as offer_name,
                o.price,
                CASE WHEN o.running_time = 0
                THEN date_add(op.date, INTERVAL o.duration MINUTE)
                ELSE o.duration END as offer_duration
            FROM offer_purchases op
            INNER JOIN offers o ON op.offer_id = o.offer_id
            LEFT JOIN offer_localizations ol ON o.offer_id = ol.offer_id AND ol.languages_id = '{language}'
            INNER JOIN payment_objects p ON op.payment_object_id = p.id AND p.id = {payment_object_id}
        """

        cursor.execute(query)
        response = []
        row = cursor.fetchall()
        for data in row:
            response.append({
                "purchase_id": data[0],
                "offer_name": data[1],
                "price": data[2],
                "offer_duration": data[3]
            })
        cursor.close()
    return response

As you can see, I build the object to return, but I would prefered return a colection of schemas in an array, similar to this:

[
 {
    Schema
 },
 {
    Schema
 },
 ...
]

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
vitalikcommented, Mar 28, 2022

Hi @JFeldaca

django-ninja is built on top of pydantic library

what you can do is use pydantic’s dataclass - that allows you to pass argumennts as args instead of kwargs:

from pydantic.dataclasses import dataclass

@dataclass
class TicketHistorySchemaOut:
     purchase_id: int
     offer_name: str
     price: int
     offer_duration: int
 
...

rows = cursor.fetchall()
items = [TicketHistorySchemaOut(*i) for i in rows]


0reactions
vitalikcommented, Mar 29, 2022

@JFeldaca right… you need to conert each item to dict

return [TicketHistorySchemaOut(*data).dict() for data in rows]
# ......................................^
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use INFORMATION_SCHEMA Views in SQL Server
INFORMATION_SCHEMA Views allow you to find what tables are in your schema. ... This first query will return all of the tables in...
Read more >
How To - Get the Database Schema using SQL - Getting Started
DECLARE @fkref as NCHAR(50); SET @fkref = SELECT objectId from [database schema] WHERE typeid = 1 and name = 'FileLinks'; SELECT EXISTS( SELECT...
Read more >
Get SQL Server schema via a SQL query? - Stack Overflow
The INFORMATION_SCHEMA schema is a good place to start: SELECT * FROM INFORMATION_SCHEMA.TABLES SELECT * FROM INFORMATION_SCHEMA.VIEWS.
Read more >
Using database schemas in SQL Server - The Quest Blog
Listing all database schemas in the current database. You can get a list of the schemas using an SSMS or T-SQL query. To...
Read more >
A Walkthrough of SQL Schema - SQLShack
In this blog post, gives an overview of SQL Schema and its usage in SQL Server. We define SQL Schema as a logical...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found