如何为 Django 的数据模型编写此类(从 Propel 的 YML 格式转换)
我正在将当前使用 Propel ORM 的 Web 项目转换为 django 项目。
我的第一个任务是将模型模式“移植”到 django 的模式。
我已阅读 django 文档,但它们似乎不够详细。举个例子,我如何“移植”在 Propel YML 模式中定义的(人为的)表,如下所示:
demo_ref_country:
code: { type: varchar(4), required: true, index: unique }
name: { type: varchar(64), required: true, index: unique }
geog_region_id: { type: integer, foreignTable: demo_ref_geographic_region, foreignReference: id, required: true, onUpdate: cascade, onDelete: restrict }
ccy_id: { type: integer, foreignTable: demo_ref_currency_def, foreignReference: id, required: true, onUpdate: cascade, onDelete: restrict }
flag_image_path: { type: varchar(64), required: true, default: ''}
created_at: ~
_indexes:
idx_f1: [geog_region_id, ccy_id, created_at]
_uniques:
idxu_f1_key: [code, geog_region_id, ccy_id]
这是迄今为止我的(无力的)尝试:
class Country(models.Model):
code = models.CharField(max_length=4) # Erm, no index on this column .....
name = models.CharField(max_length=64) # Erm, no index on this column .....
geog_region_id = models.ForeignKey(GeogRegion) # Is this correct ? (how about ref integrity constraints ?
ccy_id = models.ForeignKey(Currency) # Is this correct?
flag_image_path = models.CharField(max_length=64) # How to set default on this col?
created_at = models.DateTimeField() # Will this default to now() ?
# Don't know how to specify indexes and unique indexes ....
[编辑]
对于所有建议我的人RTFM,我理解您的沮丧。只是文档对我来说不是很清楚。这可能是一种 Python 式的文档方式 - 但由于我有 C++ 背景,我觉得文档可以改进,让来自不同语言的人更容易理解。
举个例子:文档仅说明了构造函数中的类名和 **options 参数,但没有告诉您可能的选项是什么。
例如 class CharField(max_length=None,[**options])
文档中还有一行给出了允许的选项列表,这些选项适用于所有字段类型。
但是,选项以以下形式提供:
Field.optionname
我不清楚类属性和构造函数参数之间的(显然是隐式的)链接。看起来,如果一个类有一个属性 foo,那么这意味着你可以将一个名为 foo 的参数传递给它的构造函数。这个观察结果是否适用于所有 Python 类?
I am converting a web project that currently uses the Propel ORM, to a django project.
My first task is to 'port' the model schema to django's.
I have read the django docs, but they do not appear to be in enough detail. Case in point, how may I 'port' a (contrived) table defined in the Propel YML schema as follows:
demo_ref_country:
code: { type: varchar(4), required: true, index: unique }
name: { type: varchar(64), required: true, index: unique }
geog_region_id: { type: integer, foreignTable: demo_ref_geographic_region, foreignReference: id, required: true, onUpdate: cascade, onDelete: restrict }
ccy_id: { type: integer, foreignTable: demo_ref_currency_def, foreignReference: id, required: true, onUpdate: cascade, onDelete: restrict }
flag_image_path: { type: varchar(64), required: true, default: ''}
created_at: ~
_indexes:
idx_f1: [geog_region_id, ccy_id, created_at]
_uniques:
idxu_f1_key: [code, geog_region_id, ccy_id]
Here is my (feeble) attempt so far:
class Country(models.Model):
code = models.CharField(max_length=4) # Erm, no index on this column .....
name = models.CharField(max_length=64) # Erm, no index on this column .....
geog_region_id = models.ForeignKey(GeogRegion) # Is this correct ? (how about ref integrity constraints ?
ccy_id = models.ForeignKey(Currency) # Is this correct?
flag_image_path = models.CharField(max_length=64) # How to set default on this col?
created_at = models.DateTimeField() # Will this default to now() ?
# Don't know how to specify indexes and unique indexes ....
[Edit]
To all those suggesting that I RTFM, I understand your frustration. Its just that the documentation is not very clear to me. It is probably a Pythonic way of documentation - but coming from a C++ background, I feel the documentation could be improved to make it more accesible for people coming from different languages.
Case in point: the documentation merely states the class name and an **options parameter in the ctor, but doesn't tell you what the possible options are.
For example class CharField(max_length=None,[**options])
There is a line further up in the documentation that gives a list of permissible options, which are applicable to all field types.
However, the options are provided in the form:
Field.optionname
The (apparently implicit) link between a class property and a constructor argument was not clear to me. It appears that if a class has a property foo, then it means that you can pass an argument named foo to its constructor. Does that observation hold true for all Python classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
索引是自动生成的,供您引用其他模型(即您的外键)。换句话说:您的 geog_region_id 是正确的(但将其称为 geog_region 会更好)。
您可以使用默认字段选项设置默认值。
The indexes are automatically generated for your references to other models (i.e. your foreign keys). In other words: your geog_region_id is correct (but it would be better style to call it geog_region).
You can set default values using the default field option.
(我不是 propel 的 orm 方面的专家)
Django 总是尝试模仿“删除时级联”行为,因此无需在某处指定。默认情况下,除非另有指定,否则所有字段都是必需的。
对于日期时间字段,请参阅更多选项此处< /a>.所有常规字段选项此处。
(I'm no expert on propel's orm)
Django always tries to imitate the "cascade on delete" behaviour, so no need to specify that somewhere. By default all fields are required, unless specified differently.
For the datetime field see some more options here. All general field options here.
您可以传递
unique = True
上述两者的关键字参数和值。如果
GeogRegion
和Currency
在此模型之前定义,则以上行是正确的。否则,请在型号名称周围加上引号。例如models.ForeignKey(“GeogRegion”)
。请参阅文档。简单的。使用
default = "/foo/bar"
关键字参数和值。不是自动的。您可以执行
default = datetime.now
< /a> (记住首先from datetime import datetime
)。或者,您可以指定auto_now_add = 真
。看看
unique_together
。您会看到我链接到的文档与其他人指出的文档相同。我强烈建议您阅读文档并完成教程。
You can pass the
unique = True
keyword argument and value for both of the above.The above lines are correct if
GeogRegion
andCurrency
are defined before this model. Otherwise put quotes around the model names. For e.g.models.ForeignKey("GeogRegion")
. See documentation.Easy. Use the
default = "/foo/bar"
keyword argument and value.Not automatically. You can do
default = datetime.now
(remember to firstfrom datetime import datetime
). Alternately you can specifyauto_now_add = True
.Take a look at
unique_together
.You'll see that the document I have linked to is the same pointed out by others. I strongly urge you to read the docs and work through the tutorial.
抱歉,您还没有阅读文档。在 字段参考页面准确地揭示了如何设置这些选项。
评论后编辑我不明白你所说的多行是什么意思。 Python 不关心你在括号内使用了多少行 - 所以这:
与此完全相同:
Django 不支持多列主键,但如果你只想要多列唯一约束,请参阅 unique_together。
I'm sorry, you haven't read the docs. A simple search for
index
,unique
ordefault
on the field reference page reveals exactly how to set those options.Edit after comment I don't understand what you mean about multiple lines. Python doesn't care how many lines you use within brackets - so this:
is exactly the same as this:
Django doesn't support multi-column primary keys, but if you just want a multi-column unique constraint, see unique_together.
可以设置默认值,db_index参数为相关字段创建索引。您可以对单独的字段使用 unique=True,但将 unique 放在一起将检查列中的唯一性。
更新:首先,我建议您仔细阅读文档,因为 django 给了您很多机会,其中一些有一些限制...例如,unique_together 选项仅用于 django admin 。这意味着如果您创建新记录或通过管理界面编辑它,它将被使用。如果您还使用其他方式插入数据(例如 DataModel.objects.create 语句),最好在字段定义中使用 uniaue=True ,例如:
ForeignKey 字段默认是唯一的,因此您不需要为它们定义唯一性。
Django 支持方法重写,因此您可以根据需要重写模型保存和删除方法。
在此处查看。 Django 还允许您编写原始 sql 查询您可以在此处查看
正如我所解释的,django 管理功能是独一无二的。因此,不要忘记将 unique=True 添加到必填字段。
唯一一起还允许您定义不同的唯一对,例如;
这意味着,id和代码必须是唯一的和代码,ccy和geog_region必须是唯一的
更新2:在你的问题更新之前......
最好从教程。它用很好的例子定义了基础知识。
至于文档风格,让我给你举个例子,但如果你从导师开始,对你来说会更容易......
有来自模型结构... Doc here
定义了数据库字段的基本结构,使用(),并且有一些参数作为选项。这就是部分:
由于这是一个字段结构,可用选项定义为:
所以,
这是一般用法。由于 uniqu 是适用于所有字段类型的基本选项,因此它被归类为 field.unique。有一些选项可用于单个字段类型,例如对称(ManyToMany 字段选项),被分类为 ManyToMany.Symmetrical
对于 queryset
当你使用函数时使用,但你用它来过滤模型,换句话说,编写一个过滤查询来执行......它有一些方法,就像过滤器一样...
因为这需要一些kwargs,并且正如我之前所说,这用于过滤您的查询结果,因此kwargs必须是您的模型字段(数据库表字段),例如:
文档中定义了什么对象,但是它是一个帮助您获取相关对象的管理器。
文档包含很好的例子,但你必须从导师开始,这就是我可以建议你的......
You can set default values,, db_index paramaeter creates indexes for related fields. You can use unique=True for seperate fields, but tahat unique together will check uniqueness in columns together.
UPDATE: First of all, i advice you to read documentatin carefully, since django gives you a lot of opportunuties, some of them have some restrictions... Such as, unique_together option is used just for django admin. It means if you create a new record or edit it via admin interface, it will be used. If you will alsa insert data with other ways (like a DataModel.objects.create statement) its better you use uniaue=True in field definition like:
ForeignKey fields are unique as default, so you do not need to define uniqueness for them.
Django supports method override, so you can override Model save and delete methods as you like.
check it here. Django also allows you to write raw sql queries you can check it here
As i explained, unique together is a django admin feature. So dont forget to add unique=True to required fields.
Unique together also allows you to define diffrent unique pairs, such as;
That means, id and code must be unique together and code, ccy and geog_region must be unique together
UPDATE 2: Prior to your question update...
It is better yo start from tutorials. It defines basics with good examples.
As for doc style, let me give you an example, but if you start from tutors, it will be easier for you...
There are from model structure... Doc here
that defines, the basic structure of a database field, () is used, and it has some parameters taken as options. that is the part:
Since this is a field struvture, available options are defines as:
So,
That is the general usage. Since uniqu is a basic option available to all field types, it classified as field.unique. There are some options available to a single field type, like symmetrical which is a ManyToMany field option, is classified as ManyToMany.Symmetrical
For the queryset
That is used as you use a function, but you use it to filter a model, with other words, write a filter query to execute... It has some methods, like filter...
Since this takes some kwargs, and as i told before, this is used to filter your query results, so kwargs must be your model fields (database table fields) Like:
what object is defines in the doc, but it is a manager that helps you get related objects.
Doc contains good examples, but you have to start from tutors, that is what i can advice you...