Package: djantic
DjanticPydanticmodel support forDjangoDocumentation: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.QuickstartInstall using pip:pipinstalldjanticCreate a model schema:fromusers.modelsimportUserfromdjanticimportModelSchemaclassUserSchema(ModelSchema):classConfig:model=Userprint(UserSchema.schema())Output:{"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"],}Seehttps://pydantic-docs.helpmanual.io/usage/models/for more.Loading and exporting model instancesUse thefrom_ormmethod on the model schema to load a Django model instance forexport:user=User.objects.create(first_name="Jordan",last_name="Eremieff",email="jordan@eremieff.com")user_schema=UserSchema.from_orm(user)print(user_schema.json(indent=2))Output:{"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 relationsDjantic 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:# models.pyfromdjango.dbimportmodelsclassOrderUser(models.Model):email=models.EmailField(unique=True)classOrderUserProfile(models.Model):address=models.CharField(max_length=255)user=models.OneToOneField(OrderUser,on_delete=models.CASCADE,related_name='profile')classOrder(models.Model):total_price=models.DecimalField(max_digits=8,decimal_places=5,default=0)user=models.ForeignKey(OrderUser,on_delete=models.CASCADE,related_name="orders")classOrderItem(models.Model):price=models.DecimalField(max_digits=8,decimal_places=5,default=0)quantity=models.IntegerField(default=0)order=models.ForeignKey(Order,on_delete=models.CASCADE,related_name="items")classOrderItemDetail(models.Model):name=models.CharField(max_length=30)order_item=models.ForeignKey(OrderItem,on_delete=models.CASCADE,related_name="details")# schemas.pyfromdjanticimportModelSchemafromorders.modelsimportOrderItemDetail,OrderItem,Order,OrderUserProfileclassOrderItemDetailSchema(ModelSchema):classConfig:model=OrderItemDetailclassOrderItemSchema(ModelSchema):details:List[OrderItemDetailSchema]classConfig:model=OrderItemclassOrderSchema(ModelSchema):items:List[OrderItemSchema]classConfig:model=OrderclassOrderUserProfileSchema(ModelSchema):classConfig:model=OrderUserProfileclassOrderUserSchema(ModelSchema):orders:List[OrderSchema]profile:OrderUserProfileSchemaNow 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:user=OrderUser.objects.first()print(OrderUserSchema.from_orm(user).json(ident=4))Output:{"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 fieldsThe fields exposed in the model instance may be configured using two options:includeandexclude. 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 modelexcepta field namedemail_address, you would use theexcludeoption:classUserSchema(ModelSchema):classConfig:exclude=["email_address"]In addition to this, you may also limit the fields toonlyinclude annotations from the model schema class by setting theincludeoption to a special string value:"__annotations__".classProfileSchema(ModelSchema):website:strclassConfig:model=Profileinclude="__annotations__"assertProfileSchema.schema()=={"title":"ProfileSchema","description":"A user's profile.","type":"object","properties":{"website":{"title":"Website","type":"string"}},"required":["website"]}