我应该使用 ArrayField 还是 ManyToManyField 作为标签 [英] Should I use ArrayField or ManyToManyField for tags

查看:28
本文介绍了我应该使用 ArrayField 还是 ManyToManyField 作为标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 django 中为 postgres 数据库的模型添加标签,我找到了两个解决方案:

I am trying to add tags to a model for a postgres db in django and I found two solutions:

使用外键:

class Post(models.Model):
    tags = models.ManyToManyField('tags')
    ...

class Tag(models.Model):
    name = models.CharField(max_length=140)

使用数组字段:

from django.contrib.postgres.fields import ArrayField

class Post(models.Model):
    tags = ArrayField(models.CharField(max_length=140))
    ...

假设我不关心在我的代码中支持其他数据库后端,推荐的解决方案是什么?

assuming that I don't care about supporting other database-backends in my code, what is a recommended solution ?

推荐答案

如果您使用数组字段,

  • 数据库中每一行的大小会有点大,因此 Postgres 将使用更多 toast 表

每次获取行时,除非您专门使用 延迟 该字段或以其他方式仅通过或值或其他方式将其从查询中排除,每次遍历该行时,您都需要支付加载所有这些值的成本.如果这就是您所需要的,那就这样吧.

Every time you get the row, unless you specifically use defer the field or otherwise exclude it from the query via only, or values or something, you paying the cost of loading all those values every time you iterate across that row. If that's what you need then so be it.

基于该数组中的值进行过滤,虽然可能不会那么好,而且 Django ORM 并没有像 M2M 表那样明显.

Filtering based on values in that array, while possible isn't going to be as nice and the Django ORM doesn't make it as obvious as it does for M2M tables.

如果您使用 M2M 领域,

If you use M2M field,

  • 您可以更轻松地过滤这些相关值这些字段默认被推迟,如果你需要它们,你可以使用 prefetch_related ,然后如果你只想加载这些值的一个子集.

  • You can filter more easily on those related values Those fields are postponed by default, you can use prefetch_related if you need them and then get fancy if you want only a subset of those values loaded.

由于键和额外的 id 字段,使用 M2M 时,数据库中的总存储量会略高.

Total storage in the DB is going to be slightly higher with M2M because of keys, and extra id fields.

在这种情况下,由于键的存在,连接的成本完全可以忽略不计.

The cost of the joins in this case is completely negligible because of keys.

话虽如此,以上答案不属于我.不久前,我在学习 Django 时偶然发现了这个困境.我在这个问题中找到了答案,Django Postgres ArrayField vs One-多对多关系.

With that being said, the above answer doesn't belong to me. A while ago, I had stumbled upon this dilemma when I was learning Django. I had found the answer here in this question, Django Postgres ArrayField vs One-to-Many relationship.

希望你得到你想要的.

这篇关于我应该使用 ArrayField 还是 ManyToManyField 作为标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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