56 lines
2.0 KiB
Python
56 lines
2.0 KiB
Python
# combo - content management system
|
|
# Copyright (C) 2017-2018 Entr'ouvert
|
|
#
|
|
# This program is free software: you can redistribute it and/or modify it
|
|
# under the terms of the GNU Affero General Public License as published
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
# (at your option) any later version.
|
|
#
|
|
# This program is distributed in the hope that it will be useful,
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
# GNU Affero General Public License for more details.
|
|
#
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
import json
|
|
|
|
from django.core import serializers
|
|
from django.db import models
|
|
|
|
class AssetManager(models.Manager):
|
|
def get_by_natural_key(self, key):
|
|
return self.get(key=key)
|
|
|
|
|
|
class Asset(models.Model):
|
|
objects = AssetManager()
|
|
|
|
key = models.CharField(max_length=128, unique=True)
|
|
asset = models.FileField(upload_to='assets')
|
|
|
|
@classmethod
|
|
def export_all_for_json(cls):
|
|
return [x.get_as_serialized_object() for x in Asset.objects.all()]
|
|
|
|
def get_as_serialized_object(self):
|
|
serialized_asset = json.loads(serializers.serialize('json', [self],
|
|
use_natural_foreign_keys=True, use_natural_primary_keys=True))[0]
|
|
del serialized_asset['model']
|
|
del serialized_asset['pk']
|
|
return serialized_asset
|
|
|
|
@classmethod
|
|
def load_serialized_objects(cls, json_site):
|
|
for json_asset in json_site:
|
|
cls.load_serialized_object(json_asset)
|
|
|
|
@classmethod
|
|
def load_serialized_object(cls, json_asset):
|
|
json_asset['model'] = 'assets.asset'
|
|
asset, created = Asset.objects.get_or_create(key=json_asset['fields']['key'])
|
|
json_asset['pk'] = asset.id
|
|
asset = next(serializers.deserialize('json', json.dumps([json_asset]), ignorenonexistent=True))
|
|
asset.save()
|