GVKun编程网logo

如何让Django AutoFields以更高的数字开头(django decimal)

2

本文将介绍如何让DjangoAutoFields以更高的数字开头的详细情况,特别是关于djangodecimal的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将

本文将介绍如何让Django AutoFields以更高的数字开头的详细情况,特别是关于django decimal的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于ArrayField内的Django JSONField、AutoField的话就报错:''AutoField'' object has no attribute ''rel''、Custom Fields in Django、Dirty fields in django的知识。

本文目录一览:

如何让Django AutoFields以更高的数字开头(django decimal)

如何让Django AutoFields以更高的数字开头(django decimal)

对于我们的Django应用,我们希望AutoField从1以外的数字开始。似乎没有一种明显的方法。有任何想法吗?

答案1

小编典典

就像其他人所说的那样,在数据库方面比在Django方面容易得多。

对于Postgres,就像这样:ALTER SEQUENCE sequence_name RESTART WITH12345;查看您自己的数据库引擎的文档,了解如何在其中进行操作。

ArrayField内的Django JSONField

ArrayField内的Django JSONField

我在使用带有JSONField的ArrayField插入字段时遇到问题。

models.py

locations = ArrayField(JSONField(null = True,blank = True), blank=True, null = True)

插入

location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]instance.locations = location_arrinstance.save()

当我这样做时,我得到了

`column “locations” is of type jsonb[] but expression is of type text[]

LINE 1: …d” = 2517, “locations” = ARRAY[‘{“loc…

Hint: You will need to rewrite or cast the expression.`

所以我尝试使用以下方法转储它:

import jsonlocation_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]instance.locations = json.dumps(location_arr)instance.save()

然后我得到了

`LINE 1: …d” = 2517, “locations” = ‘[{“loc”:…

DETAIL: “[” must introduce explicitly-specified array dimensions.`

我在用:

  1. Django 1.9
  2. Python 2.7
  3. PostgreSQL 9.4.10
  4. psycopg2 2.6.2

答案1

小编典典

数组
首先,让我们仔细看看Postgresql Arrays文档中的这一重要文本。

提示:数组不是集合;搜索特定的数组元素可能是数据库设计错误的标志。考虑使用单独的表,该表的每个行都将是一个数组元素。这将更易于搜索,并且可能会针对大量元素进行更好地缩放。

大多数时候,你不应该使用数组。

JSONB
JSONB在Django中可用作JSONField类型。该字段比数组字段更具可伸缩性和灵活性,并且可以更高效地进行搜索。但是,如果你发现自己一直在JSONB字段中进行搜索,则上述有关数组的声明对JSONB同样有效。

现在你的系统中有什么?一个包含JSONB字段的数组。这是一场灾难,等待发生。请规范化你的数据。

概括
那么什么时候使用ArrayField?

在极少数情况下,你不需要在该列中进行搜索,也不需要使用该列进行联接。

AutoField的话就报错:''AutoField'' object has no attribute ''rel''

AutoField的话就报错:''AutoField'' object has no attribute ''rel''

def data_inspect(self, data, extra=None):
        if isinstance(data, (QuerySet, Page, list)):
            convert_data = []
            if extra:
                for i, obj in enumerate(data):
                    convert_data.append(self.data_inspect(obj, extra.get(
                        **{self.through_fields[0]: obj, self.through_fields[1]: self.source_field})))
            else:
                for obj in data:
                    convert_data.append(self.data_inspect(obj))
            return convert_data
        elif isinstance(data, models.Model):
            obj_dict = {}
            concrete_model = data._meta.concrete_model
            for field in concrete_model._meta.local_fields:
                # 检查 field 是否存在 rel 这个属性,为''AutoField'' object has no attribute ''rel''错误填坑
                if hasattr(field, ''rel''):
                    if field.rel is None:
                        if self.check_attr(field.name) and hasattr(data, field.name):
                            obj_dict[field.name] = self.data_inspect(getattr(data, field.name))
                    else:
                        if self.check_attr(field.name) and self.foreign:
                            obj_dict[field.name] = self.data_inspect(getattr(data, field.name))
                else:
                    if self.check_attr(field.name) and hasattr(data, field.name):
                        obj_dict[field.name] = self.data_inspect(getattr(data, field.name))
            for field in concrete_model._meta.many_to_many:
                if self.check_attr(field.name) and self.many:
                    obj_dict[field.name] = self.data_inspect(getattr(data, field.name))
            for k, v in data.__dict__.items():
                if not str(k).startswith(''_'') and k not in obj_dict.keys() and self.check_attr(k):
                    obj_dict[k] = self.data_inspect(v)
            if extra:
                for field in extra._meta.concrete_model._meta.local_fields:
                    if field.name not in obj_dict.keys() and field.name not in self.through_fields:
                        if field.rel is None:
                            if self.check_attr(field.name) and hasattr(extra, field.name):
                                obj_dict[field.name] = self.data_inspect(getattr(extra, field.name))
                        else:
                            if self.check_attr(field.name) and self.foreign:
                                obj_dict[field.name] = self.data_inspect(getattr(extra, field.name))
            return obj_dict
        elif isinstance(data, manager.Manager):
            through_list = data.through._meta.concrete_model._meta.local_fields
            through_data = data.through._default_manager
            self.through_fields = [data.target_field.name, data.source_field.name]
            self.source_field = data.instance
            if len(through_list) > 3 and self.through:
                return self.data_inspect(data.all(), through_data)
            else:
                return self.data_inspect(data.all())
        elif isinstance(data, (datetime.datetime, datetime.date, datetime.time)):
            return self.time_func(data)
        elif isinstance(data, (ImageFieldFile, FileField)):
            return data.url if data.url else data.path
        elif isinstance(data, Decimal):
            return float(data)
        elif isinstance(data, dict):
            obj_dict = {}
            if self._dict_check:
                for k, v in data.items():
                    obj_dict[k] = self.data_inspect(v)
            else:
                for k, v in data.items():
                    if self.check_attr(k):
                        obj_dict[k] = self.data_inspect(v)
            return obj_dict
        elif isinstance(data, (str, bool, float, int)):
            return data
        else:
            return None

 

Custom Fields in Django

Custom Fields in Django

I was helping someone today in the Django IRC channel and the question came across about storing a denormalized data set in a single field. Typically I do such things by either serializing the data, or by separating the values with a token (comma for example).

Django has a built-in field type for CommaSeparatedIntegerField, but most of the time I’m storing strings, as I already have the integers available elsewhere. As I began to answer the person’s question by giving him an example of usage of serialization + custom properties, until I realized that it would be much easier to just write this as a Field subclass.

So I quickly did, and replaced a few lines of repetitive code with two new field classes in our source:

Update: There were some issues with my understanding of how the metaclass was working. I’ve corrected the code and it should function properly now.

SerializedDataField

This field is typically used to store raw data, such as a dictionary, or a list of items, or could even be used for more complex objects.

from django.db import models
try:
    import cPickle as pickle
except:
    import pickle
import base64

class SerializedDataField(models.TextField):
    """Because Django for some reason feels its needed to repeatedly call
    to_python even after it''s been converted this does not support strings."""
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        if value is None: return
        if not isinstance(value, basestring): return value
        value = pickle.loads(base64.b64decode(value))
        return value

    def get_db_prep_save(self, value):
        if value is None: return
        return base64.b64encode(pickle.dumps(value))

SeparatedValuesField

An alternative to the CommaSeparatedIntegerField, it allows you to store any separated values. You can also optionally specify a  token  parameter.
from django.db import models

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop(''token'', '','')
        super(SeparatedValuesField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: return
        if isinstance(value, list):
            return value
        return value.split(self.token)

    def get_db_prep_value(self, value):
        if not value: return
        assert(isinstance(value, list) or isinstance(value, tuple))
        return self.token.join([unicode(s) for s in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

Dirty fields in django

Dirty fields in django

在我的应用程序中,当保存模型时,我需要保存更改的值(旧值和新值)。任何示例或工作代码?

我需要这个来预审内容。例如,如果用户更改了模型中的某些内容,则管理员可以在单独的表中查看所有更改,然后决定是否应用它们。

答案1

小编典典
class DirtyFieldsMixin(object):    def __init__(self, *args, **kwargs):        super(DirtyFieldsMixin, self).__init__(*args, **kwargs)        self._original_state = self._as_dict()    def _as_dict(self):        return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel])    def get_dirty_fields(self):        new_state = self._as_dict()        return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])

区别在于(除了名称之外)它仅缓存本地非关系字段。换句话说,它不缓存父模型的字段(如果存在)。

还有一件事;你需要_original_state在保存后重设字典。但是我不想覆盖save()方法,因为在大多数情况下,保存后我们会丢弃模型实例。

def save(self, *args, **kwargs):    super(Klass, self).save(*args, **kwargs)    self._original_state = self._as_dict()

关于如何让Django AutoFields以更高的数字开头django decimal的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于ArrayField内的Django JSONField、AutoField的话就报错:''AutoField'' object has no attribute ''rel''、Custom Fields in Django、Dirty fields in django的相关信息,请在本站寻找。

本文标签: