pref: 优化 device api

pull/8991/head
ibuler 2022-10-20 20:06:58 +08:00
parent a450ceee91
commit 168de45da5
5 changed files with 27 additions and 16 deletions

View File

@ -3,5 +3,5 @@ from .host import *
from .database import *
from .web import *
from .cloud import *
from .network import *
from .device import *
from .permission import *

View File

@ -1,5 +1,5 @@
from assets.serializers import HostSerializer
from assets.serializers import DeviceSerializer
from assets.models import Device
from .asset import AssetViewSet
@ -11,5 +11,5 @@ class DeviceViewSet(AssetViewSet):
def get_serializer_classes(self):
serializer_classes = super().get_serializer_classes()
serializer_classes['default'] = HostSerializer
serializer_classes['default'] = DeviceSerializer
return serializer_classes

View File

@ -13,16 +13,28 @@ class AccountHistoricalRecords(HistoricalRecords):
self.included_fields = kwargs.pop('included_fields', None)
super().__init__(*args, **kwargs)
def post_save(self, instance, created, using=None, **kwargs):
if not self.included_fields:
return super().post_save(instance, created, using=using, **kwargs)
check_fields = set(self.included_fields) - {'version'}
history_attrs = instance.history.all().values(*check_fields).first()
if history_attrs is None:
return super().post_save(instance, created, using=using, **kwargs)
attrs = {field: getattr(instance, field) for field in check_fields}
history_attrs = set(history_attrs.items())
attrs = set(attrs.items())
diff = attrs - history_attrs
if not diff:
return
super().post_save(instance, created, using=using, **kwargs)
def fields_included(self, model):
fields = []
for field in model._meta.fields:
if self.included_fields is None:
if field.name not in self.excluded_fields:
fields.append(field)
else:
if field.name in self.included_fields:
fields.append(field)
return fields
if self.included_fields:
fields = [i for i in model._meta.fields if i.name in self.included_fields]
return fields
return super().fields_included(model)
class Account(BaseAccount):
@ -39,9 +51,7 @@ class Account(BaseAccount):
on_delete=models.SET_NULL, verbose_name=_("Su from")
)
version = models.IntegerField(default=0, verbose_name=_('Version'))
history = AccountHistoricalRecords(
included_fields=['id', 'secret_type', 'secret', 'version']
)
history = AccountHistoricalRecords(included_fields=['id', 'secret', 'secret_type', 'version'])
class Meta:
verbose_name = _('Account')

View File

@ -15,6 +15,7 @@ class AccountSerializerCreateMixin(serializers.ModelSerializer):
push_now = serializers.BooleanField(
default=False, label=_("Push now"), write_only=True
)
has_secret = serializers.BooleanField(label=_("Has secret"), read_only=True)
@staticmethod
def validate_template(value):

View File

@ -1086,7 +1086,7 @@ msgstr ""
#: assets/serializers/account/account.py:16
msgid "Push now"
msgstr ""
msgstr "立刻推送"
#: assets/serializers/account/account.py:24
msgid "Account template not found"