问题描述
我正在尝试在Django中为postgres db的模型添加标签,我发现了两种解决方案:
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 ?
推荐答案
如果您使用Array字段,
If you use an Array field,
-
数据库中每行的大小将变大,因此Postgres将使用更多的吐司表
每次都获得该行,除非您专门使用推迟该字段,或者仅通过,或值或某种方式将其从查询中排除,您每次在该行上进行迭代时都要付出加载所有这些值的代价.如果那是您的需要,那就这样吧.
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 valuesThose 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与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.
希望您能找到想要的东西.
Hope you get what you were looking for.
这篇关于我应该对标签使用ArrayField还是ManyToManyField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!