https://github.com/bigbuildbench/jordaneremieff_djantic

https://github.com/bigbuildbench/jordaneremieff_djantic

Science Score: 13.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Academic email domains
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (12.0%) to scientific vocabulary
Last synced: 9 months ago · JSON representation

Repository

Basic Info
  • Host: GitHub
  • Owner: BigBuildBench
  • License: mit
  • Language: Python
  • Default Branch: master
  • Size: 29.3 KB
Statistics
  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • Open Issues: 0
  • Releases: 0
Created over 1 year ago · Last pushed over 1 year ago
Metadata Files
Readme License

README.md

Djantic

Pydantic model support for Django

GitHub Workflow Status (Test) PyPi package Supported Python versions Supported Django versions


Documentation: https://jordaneremieff.github.io/djantic/


Djantic is a library that provides a configurable utility class for automatically creating a Pydantic model instance for any Django model class. It is intended to support all of the underlying Pydantic model functionality such as JSON schema generation and introduces custom behaviour for exporting Django model instance data.

Quickstart

Install using pip:

shell pip install djantic

Create a model schema:

```python from users.models import User

from djantic import ModelSchema

class UserSchema(ModelSchema): class Config: model = User

print(UserSchema.schema()) ```

Output:

python { "title": "UserSchema", "description": "A user of the application.", "type": "object", "properties": { "profile": {"title": "Profile", "description": "None", "type": "integer"}, "id": {"title": "Id", "description": "id", "type": "integer"}, "first_name": { "title": "First Name", "description": "first_name", "maxLength": 50, "type": "string", }, "last_name": { "title": "Last Name", "description": "last_name", "maxLength": 50, "type": "string", }, "email": { "title": "Email", "description": "email", "maxLength": 254, "type": "string", }, "created_at": { "title": "Created At", "description": "created_at", "type": "string", "format": "date-time", }, "updated_at": { "title": "Updated At", "description": "updated_at", "type": "string", "format": "date-time", }, }, "required": ["first_name", "email", "created_at", "updated_at"], }

See https://pydantic-docs.helpmanual.io/usage/models/ for more.

Loading and exporting model instances

Use the from_orm method on the model schema to load a Django model instance for export:

```python user = User.objects.create( firstname="Jordan", lastname="Eremieff", email="jordan@eremieff.com" )

userschema = UserSchema.fromorm(user) print(user_schema.json(indent=2)) ```

Output:

json { "profile": null, "id": 1, "first_name": "Jordan", "last_name": "Eremieff", "email": "jordan@eremieff.com", "created_at": "2020-08-15T16:50:30.606345+00:00", "updated_at": "2020-08-15T16:50:30.606452+00:00" }

Using multiple level relations

Djantic supports multiple level relations. This includes foreign keys, many-to-many, and one-to-one relationships.

Consider the following example Django model and Djantic model schema definitions for a number of related database records:

```python

models.py

from django.db import models

class OrderUser(models.Model): email = models.EmailField(unique=True)

class OrderUserProfile(models.Model): address = models.CharField(maxlength=255) user = models.OneToOneField(OrderUser, ondelete=models.CASCADE, related_name='profile')

class Order(models.Model): totalprice = models.DecimalField(maxdigits=8, decimalplaces=5, default=0) user = models.ForeignKey( OrderUser, ondelete=models.CASCADE, related_name="orders" )

class OrderItem(models.Model): price = models.DecimalField(maxdigits=8, decimalplaces=5, default=0) quantity = models.IntegerField(default=0) order = models.ForeignKey( Order, ondelete=models.CASCADE, relatedname="items" )

class OrderItemDetail(models.Model): name = models.CharField(maxlength=30) orderitem = models.ForeignKey( OrderItem, ondelete=models.CASCADE, relatedname="details" ) ```

```python

schemas.py

from djantic import ModelSchema

from orders.models import OrderItemDetail, OrderItem, Order, OrderUserProfile

class OrderItemDetailSchema(ModelSchema): class Config: model = OrderItemDetail

class OrderItemSchema(ModelSchema): details: List[OrderItemDetailSchema]

class Config:
    model = OrderItem

class OrderSchema(ModelSchema): items: List[OrderItemSchema]

class Config:
    model = Order

class OrderUserProfileSchema(ModelSchema): class Config: model = OrderUserProfile

class OrderUserSchema(ModelSchema): orders: List[OrderSchema] profile: OrderUserProfileSchema ```

Now let's assume you're interested in exporting the order and profile information for a particular user into a JSON format that contains the details accross all of the related item objects:

python user = OrderUser.objects.first() print(OrderUserSchema.from_orm(user).json(ident=4))

Output: json { "profile": { "id": 1, "address": "", "user": 1 }, "orders": [ { "items": [ { "details": [ { "id": 1, "name": "", "order_item": 1 } ], "id": 1, "price": 0.0, "quantity": 0, "order": 1 } ], "id": 1, "total_price": 0.0, "user": 1 } ], "id": 1, "email": "" }

The model schema definitions are composable and support customization of the output according to the auto-generated fields and any additional annotations.

Including and excluding fields

The fields exposed in the model instance may be configured using two options: include and exclude. These represent iterables that should contain a list of field name strings. Only one of these options may be set at the same time, and if neither are set then the default behaviour is to include all of the fields from the Django model.

For example, to include all of the fields from a user model except a field named email_address, you would use the exclude option:

python class UserSchema(ModelSchema): class Config: exclude = ["email_address"]

In addition to this, you may also limit the fields to only include annotations from the model schema class by setting the include option to a special string value: "__annotations__".

```python class ProfileSchema(ModelSchema): website: str

    class Config:
        model = Profile
        include = "__annotations__"

assert ProfileSchema.schema() == {
    "title": "ProfileSchema",
    "description": "A user's profile.",
    "type": "object",
    "properties": {
        "website": {
            "title": "Website",
            "type": "string"
        }
    },
    "required": [
        "website"
    ]
}

```

Owner

  • Name: BigBuildBench
  • Login: BigBuildBench
  • Kind: organization

abbr. B3, benchmarking the repo-level understanding capability of your LLMs by reconstructing project build-file.

GitHub Events

Total
  • Create event: 3
Last Year
  • Create event: 3

Dependencies

.github/workflows/publish.yml actions
  • actions/cache v2 composite
  • actions/checkout v2 composite
  • actions/setup-python v2 composite
.github/workflows/test.yml actions
  • actions/cache v2 composite
  • actions/checkout v2 composite
  • actions/setup-python v2 composite
pyproject.toml pypi
  • Pygments ^2.9.0 develop
  • black ^21.7b0 develop
  • bump2version ^1.0.1 develop
  • codecov ^2.1.11 develop
  • django-stubs ^1.8.0 develop
  • factory-boy ^3.2.1 develop
  • flake8 ^3.9.2 develop
  • mkautodoc ^0.1.0 develop
  • mkdocs ^1.2.3 develop
  • mkdocs-material ^7.1.10 develop
  • mypy ^0.910 develop
  • psycopg2 ^2.9.1 develop
  • pymdown-extensions ^8.2 develop
  • pytest ^6.2.4 develop
  • pytest-cov ^2.12.1 develop
  • pytest-django ^4.4.0 develop
  • rich ^10.6.0 develop
  • setuptools ^65.5.1 develop
  • twine ^3.4.1 develop
  • wheel ^0.38.1 develop
  • python ^3.7
setup.py pypi