mirror of
https://github.com/netbox-community/netbox.git
synced 2025-07-23 04:22:01 -06:00
Moved object serialization into a utility function
This commit is contained in:
parent
9d419de9dc
commit
6c1b5fdf3a
@ -5,7 +5,6 @@ import uuid
|
||||
from django.db.models.signals import post_delete, post_save
|
||||
from django.utils.functional import curry, SimpleLazyObject
|
||||
|
||||
from utilities.models import ChangeLoggedModel
|
||||
from .constants import OBJECTCHANGE_ACTION_CREATE, OBJECTCHANGE_ACTION_DELETE, OBJECTCHANGE_ACTION_UPDATE
|
||||
|
||||
|
||||
@ -13,7 +12,7 @@ def record_object_change(user, request_id, instance, **kwargs):
|
||||
"""
|
||||
Create an ObjectChange in response to an object being created or deleted.
|
||||
"""
|
||||
if not isinstance(instance, ChangeLoggedModel):
|
||||
if not hasattr(instance, 'log_change'):
|
||||
return
|
||||
|
||||
# Determine what action is being performed. The post_save signal sends a `created` boolean, whereas post_delete
|
||||
|
@ -1,11 +1,9 @@
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import json
|
||||
|
||||
from django.core.serializers import serialize
|
||||
from django.db import models
|
||||
|
||||
from extras.models import ObjectChange
|
||||
from utilities.utils import serialize_object
|
||||
|
||||
|
||||
class ChangeLoggedModel(models.Model):
|
||||
@ -32,15 +30,10 @@ class ChangeLoggedModel(models.Model):
|
||||
Create a new ObjectChange representing a change made to this object. This will typically be called automatically
|
||||
by extras.middleware.ChangeLoggingMiddleware.
|
||||
"""
|
||||
|
||||
# Serialize the object using Django's built-in JSON serializer, then extract only the `fields` dict.
|
||||
json_str = serialize('json', [self])
|
||||
object_data = json.loads(json_str)[0]['fields']
|
||||
|
||||
ObjectChange(
|
||||
user=user,
|
||||
request_id=request_id,
|
||||
changed_object=self,
|
||||
action=action,
|
||||
object_data=object_data
|
||||
object_data=serialize_object(self)
|
||||
).save()
|
||||
|
@ -1,8 +1,10 @@
|
||||
from __future__ import unicode_literals
|
||||
|
||||
import datetime
|
||||
import json
|
||||
import six
|
||||
|
||||
from django.core.serializers import serialize
|
||||
from django.http import HttpResponse
|
||||
|
||||
|
||||
@ -82,3 +84,15 @@ def dynamic_import(name):
|
||||
for comp in components[1:]:
|
||||
mod = getattr(mod, comp)
|
||||
return mod
|
||||
|
||||
|
||||
def serialize_object(obj, extra=None):
|
||||
"""
|
||||
Return a generic JSON representation of an object using Django's built-in serializer. (This is used for things like
|
||||
change logging, not the REST API.)
|
||||
"""
|
||||
json_str = serialize('json', [obj])
|
||||
data = json.loads(json_str)[0]['fields']
|
||||
if extra is not None:
|
||||
data['extra'] = extra
|
||||
return data
|
||||
|
Loading…
Reference in New Issue
Block a user