Python 如何从 django 模型创建双长文本字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32516026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:43:05  来源:igfitidea点击:

How to create double and long text field from django models

pythondjangodjango-modelsdjango-forms

提问by Rajeev

How to create a doublefield in mysql using django models. i run into this error and also how to create a longtextdatatype with django

如何double使用 Django 模型在 mysql 中创建一个字段。我遇到了这个错误以及如何longtext使用 django创建数据类型

class Test(models.Model):
   maxcount = models.DoubleField(null=True) ## double DEFAULT NULL,
   cs = models.TextField()#longtext,

Error:

错误:

    maxcount = models.DoubleField(null=True) ##double DEFAULT NULL,
    AttributeError: 'module' object has no attribute 'DoubleField'

回答by Andrey Grachev

There is no DoubleFieldin Django but FloatField[FloatField description in Django's Model field reference]creates a doubledatatype in mysql.

DoubleFieldDjango中没有,但FloatField[FloatField description in Django's Model field reference]double在 mysql 中创建了一个数据类型。

Django's TextFieldcreates a LONGTEXTtype in mysql. There is no easy way to change TextFieldbehaviour to create e.g. MEDIUMTEXTtype in mysql. But one can create a custom model field to achieve that: Writing custom model fields

Django在 mysql 中TextField创建了一个LONGTEXT类型。没有简单的方法可以更改TextField行为以MEDIUMTEXT在 mysql 中创建例如类型。但是可以创建一个自定义模型字段来实现:编写自定义模型字段

回答by coya

I think you might be needing DecimalField: https://docs.djangoproject.com/en/2.0/ref/models/fields/#decimalfield. It works well with MySQL, and you could also use this for integer values.

我认为您可能需要 DecimalField:https: //docs.djangoproject.com/en/2.0/ref/models/fields/#decimalfield。它适用于 MySQL,您也可以将其用于整数值。

Declare the fields in your models

声明模型中的字段

balance = models.DecimalField(max_digits=20, decimal_places=2, default=Decimal(0.00))

Also, consider defining a decimal context to create your actual values like so:

此外,考虑定义一个十进制上下文来创建您的实际值,如下所示:

# defined in the settings.py file.
DECIMAL_CONTEXT = Context(prec=6, rounding=ROUND_DOWN)

This will ensure compatible decimal objects through your application, and create values like this:

这将确保通过您的应用程序兼容十进制对象,并创建如下值:

DECIMAL_CONTEXT.create_decimal(0)
DECIMAL_CONTEXT.create_decimal(500)
DECIMAL_CONTEXT.create_decimal(5)
DECIMAL_CONTEXT.create_decimal(0.50)