尝试使用Django中的外键列表创建PostgreSQL字段 [英] Trying to make a PostgreSQL field with a list of foreign keys in Django

查看:187
本文介绍了尝试使用Django中的外键列表创建PostgreSQL字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我要执行的操作:
在Django中创建一个模型,该模型是PostgreSQL数组(数据库特定类型),其中包含指向另一个模型的外键。

Here is what I'm trying to do: Make a model in Django that is a PostgreSQL array (database specific type), which contains foreign keys to another model.

class Books(models.Model):
authors = ArrayField(
    models.ForeignKey('my_app.Authors', default=None, null=True, blank=True),
    blank=True,
    default=list()
)

当我尝试进行迁移时,Django给了我这个错误:

When I try to makemigrations, Django gives me this error:


SystemCheckError:系统检查确定了一些问题:

SystemCheckError: System check identified some issues:

错误:

my_app.Books.authors:(postgres.E002)数组的基字段不能为一个相关的字段。

my_app.Books.authors: (postgres.E002) Base field for array cannot be a related field.

关于如何击败它的任何想法?

Any Ideas on how to beat that?

推荐答案

您无法创建外键数组。这不是Django的限制,它是PostgreSQL的限制。

You can't create an array of foreign keys. It is not a Django limitation, it is a PostgreSQL "limitation".

原因是外键不是类型,而是对字段的约束。

The reason is that a foreign key is not a type, it is a constraint on a field. An array of foreign keys does not make any sens.

实现此目的的一般方法是使用中间表,该中间表将用作两个其他表之间的链接:

The general approach to achieve this is to use an intermediate table that will be used as a link between two others :

Authors(id, name)
Books(id, title, pub_date)
BookAuthors(id, book_id, author_id)

在上述示例中, BookAuthors.book_id Books.id 的外键,而 BookAuthors.author_id 是<$ c $的外键c> Authors.id 。因此,表 BookAuthors 用于将作者与一本书匹配,反之亦然。

In the above exemple, BookAuthors.book_id is a foreign key to Books.id and BookAuthors.author_id is a foreign key to Authors.id. Thus, the table BookAuthors is used to match an author with a book and vice versa.

Django将该中间物抽象出来 ManyToManyField 字段

Django abstracts this intermediate table with ManyToManyField fields:

class Authors(models.Model):
    name = models.CharField(...)

class Books(models.Model):
    title = models.CharField(...)
    pub_date = models.DateField(...)
    authors = models.ManyToManyField('my_app.Authors',
                                     related_name='authored_books')

在后台,Django将创建中间表。

Behind the scenes, Django will create the intermediate table.

然后,您可以使用来获得一本书的所有作者。 book.authors.all()或作者使用 author.authored_books.all()创作的所有图书。

Then, you can get all authors of a book using book.authors.all(), or all books authored by an author using author.authored_books.all().

这篇关于尝试使用Django中的外键列表创建PostgreSQL字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆