【发布时间】:2018-11-05 08:27:13
【问题描述】:
我正在尝试使用 Django 惊人的 ORM 简单地创建 one to many 类别关系模型。
SQL:
create table categories(
id serial primary key not null,
parent_id int
);
insert into categories values(default,default,default);
update categories set parent_id = 1 where id > 1;
select * from categories;
id | parent_id
----+-----------
2 | 1
3 | 1
1 |
(3 rows)
Django 惊人的 orm 模型:
class Categories(models.Model):
id = models.AutoField(primary_key=True)
parent_id = models.ForeignKey('self')
class Meta:
managed = False
db_table = 'categories'
Django 查询:
Categories.objects.get(id=1)
输出:
django.db.utils.ProgrammingError: column categories.parent_id_id does not exist
LINE 1: SELECT "categories"."id", "categories"."parent_id_id" FROM "...
^
HINT: Perhaps you meant to reference the column "categories.parent_id".
为什么它使用parent_id_id 列而不是parent_id 以及如何强制它使用parent_id?
编辑
我刚刚将 parent_id 字段更改为 parent。
编辑 2
tatlar 答案不是我的情况,因为我已经有了数据库架构。
因此,在深入研究有关 stackoverflow 的文档和其他问题之后,我得到了结果。该模型包含对每一行的父子类别的引用。它可以被所有类似图形的数据模型(cmets、类别等)继承。
class Categories(models.Model):
id = models.AutoField(primary_key=True)
parent = models.ForeignKey('self', on_delete=None, parent_link=True, related_name='children')
class Meta:
managed = False
db_table = 'categories'
获取类别 1 的所有孩子:
from myapp.models import Categories
ch = Categories.objects.get(id=1).children print (ch)
# <QuerySet [<Categories: Categories object (2)>, <Categories: Categories object (3)>]>
获取类别 2 的父级:
from myapp.models import Categories
ch = Categories.objects.get(id=1).parent
print (ch)
# <Categories: Categories object (1)>
【问题讨论】:
-
你不需要指定
parent_idDjango 将......只需将字段命名为parent -
很高兴您找到了解决方案!为了将来参考,最佳 SO 实践是不要在原始 question 中发布您自己的 SO answer(它不再是问题!)。如果您自己对原始问题的回答(在 Answer 部分中)被认为是正确的并得到 SO 社区的支持,那么它将成为规范的解决方案。
标签: django activerecord django-models