How to convert django ManyToManyField into Django-nonrel Field?

怎甘沉沦 提交于 2019-12-06 11:52:25

There's two ways to do this. The cheaper version is to use ListFields

from djangotoolbox.fields import ListField

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    cates = ListField(models.ForeignKey(shop.Cate))

The ListField simply stores a list of Cate ids. There's some important limitations to this.

  1. Your entity is limited to 1MB, so this limits the number of entities in your list. In this case, it'll still be a fairly large number, especially since there's nothing else in your entity.

  2. You can do dataastore queries against the cates field if it's indexed. However, each entity has a limit of 5000 indexes. You'll use one for the user attribute, so in this case, your cates list will be limited to have 5000 entries. I haven't hit this before so I don't know how it would fail, I presume you'd get an exception on writing your entity.

The more expensive option is to use an intermediate mapping entity. This gives you unlimited relations for the extra expense of creating/querying the mapping entities.

class UserCateMapping(models.Model)
    user = models.ForeignKey(UserProfile)
    cate = models.ForeignKey(Cate)

In this case, you'll need to create a new entity for each relation, and query for the UserCateMapping entities before fetching the actual Cate or UserProfile entity you actually want to use. It's going to be more costly than the first option, but you'll have unlimited mappings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!