Skip to content

数据库#

自定义数据表#

插件可以拥有自己的数据表,只需要在根目录下创建models.py文件,使用Django ORM标准写法即可。

插件数据库版本更新也是遵循Django的原则,开发者需要自行运行makemigrations

migrate会在加载插件前自动运行

models.py
from django.db import models
from arkid.core.translation import gettext_default as _
from django.apps import AppConfig

app_label = "com_longgui_case"

class CaseApp(AppConfig):
    name = app_label

class CaseModel(models.Model):
    class Meta:
        app_label = app_label

    nickname = models.CharField(verbose_name=_('nickname', '昵称'), max_length=128)

提示

在models.py中一定要声明AppConfig, 在创建Model时也需要声明其app_label

makemigrations command:

python manage.py makemigrations {app_label}

扩展内核数据表#

在arkid.core.models中定义的数据表,凡是继承自 ExtendModel 类的,都是默认可以进行直接扩展的model。

建议扩展的model类有:

在插件中,定义一个model,其外键为以上这些类即可。为了方便此操作,在arkid.core.models中已经定义好了这些抽象类,可以直接继承即可。

定义好model后,需要调用 arkid.core.extension.Extension.register_extend_field 注册,之后就可以直接进行查询,保存,删除操作

  • 查询: {model}.expand_objects
  • 新建或修改: {model}.save()
  • 删除: {model}.delete()
models.py
from django.db import models
from arkid.core.expand import create_expand_abstract_model
from arkid.core.translation import gettext_default as _
from django.apps import AppConfig
from arkid.core.models import UserExpandAbstract

app_label = "com_longgui_case"

class LongguiCaseAppConfig(AppConfig):
    name = app_label

class CaseUser(UserExpandAbstract):
    class Meta:
        app_label = app_label

    nickname = models.CharField(verbose_name=_('nickname', '昵称'), max_length=128)
__init__.py
from arkid.core import extension 
from arkid.core.translation import gettext_default as _
from arkid.core.models import User
from .models import CaseUser
from typing import List, Optional
from pydantic import Field

package = 'com.longgui.case'

UserSchema = extension.create_extension_schema(
    'UserSchema',
    package,
    fields=[
        ('username', str, Field()),
        ('nickname', Optional[str], Field()),
    ]
)

class CaseExtension(extension.Extension):
    def load(self):
        super().load()
        self.register_extend_field(CaseUser, 'nickname')
        self.register_api('/test/', 'POST', self.post_handler, tenant_path=True)
        self.register_api('/test/', 'GET', self.get_handler, response=List[UserSchema], tenant_path=True)

    def post_handler(self, request, tenant_id:str, data:UserSchema):
        tenant = request.tenant
        user = User()
        user.tenant = tenant
        user.username = data.username
        user.nickname = data.nickname
        user.save()

    def get_handler(self, request, tenant_id:str, ):
        users = User.expand_objects.filter(tenant=request.tenant).all()
        return list(users)

extension = CaseExtension(
    package=package,
    description="",
    version='1.0',
    labels='case',
    homepage='https://www.longguikeji.com',
    logo='',
    author='wely',
)

评论