如何在Django模型上存储字典? [英] How to store a dictionary on a Django Model?

查看:99
本文介绍了如何在Django模型上存储字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Django模型中存储一些数据。这些数据不等于模型的所有实例。



起初我想到了子类化模型,但是我试图保持应用程序的灵活性。如果我使用子类,我需要在每次需要一个新类型的对象时创建一个整个类,这并不好。我也会得到很多子类,只能存储一对额外的字段。



我真的觉得字典会是最好的方法,但没有什么在Django文档中关于在Django模型中存储字典(或者我找不到它)。



任何线索?

解决方案

如果它真的是字典,就像你正在寻找的任意数据一样,您可以使用一个两个级别的设置,一个模型是一个容器,另一个是键值对的模型。您将创建一个容器的实例,创建每个键值实例,并将一组键值实例与容器实例相关联。类似:

  class Dicty(models.Model):
name = models.CharField(max_length = 50)

class KeyVal(models.Model):
container = models.ForeignKey(Dicty,db_index = True)
key = models.CharField(max_length = 240,db_index = True)
value = models.CharField(max_length = 240,db_index = True)

但它会让您使用数据库访问/搜索字典的内部,而pickle / serialize解决方案将不会。


I need to store some data in a Django model. These data are not equal to all instances of the model.

At first I thought about subclassing the model, but I’m trying to keep the application flexible. If I use subclasses, I’ll need to create a whole class each time I need a new kind of object, and that’s no good. I’ll also end up with a lot of subclasses only to store a pair of extra fields.

I really feel that a dictionary would be the best approach, but there’s nothing in the Django documentation about storing a dictionary in a Django model (or I can’t find it).

Any clues?

解决方案

If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the container instance. Something like:

class Dicty(models.Model):
    name      = models.CharField(max_length=50)

class KeyVal(models.Model):
    container = models.ForeignKey(Dicty, db_index=True)
    key       = models.CharField(max_length=240, db_index=True)
    value     = models.CharField(max_length=240, db_index=True)

It's not pretty, but it'll let you access/search the innards of the dictionary using the DB whereas a pickle/serialize solution will not.

这篇关于如何在Django模型上存储字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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