在Django中将未知对象类型保存到数据库中 [英] Saving an unknown object type into database in Django

查看:263
本文介绍了在Django中将未知对象类型保存到数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:

class Parameter(models.Model):
    par_type = = models.CharField(max_length=30)
    value = models.TextField()

value字段存储数字(value=3.2118)的大多数时间.但是有时我想分配其他对象ID(如value="[32, 22, 45]")或字符串对象(如value="pass")等的列表.我将基于par_type:

Majority of the time the value field will store a number (value=3.2118). But sometimes I want to assign a list of other object IDs (like value="[32, 22, 45]") or a string object (like value="pass"), etc. I will use value field in functions like the ones below based on the value of par_type:

def foo(par): # par is a Parameter object.
    return float(par.value) / 2

def bar(par):
    # Some code to convert a par to a list of objects
    object_list = get_objects(par) 
    # Return a random object from list
    return random.choice(object_list)

我不想为每种可能的对象类型编写一段代码.理想情况下,在任何地方都可以使用一个decompose()函数.我想到将对象保存为pickleJSON类型(从中看到)这里).但是我不知道该怎么做.我正在使用MySQL数据库.

I don't want to write a piece of code for every possible object type. Ideally there is one decompose() function to use everywhere. I thought of saving object as pickle or JSON type (saw it from here). But I couldn't figured out how to do it. I'm using MySQL db.

推荐答案

您可以使用用法:

In: b = Foo.objects.create(value=1)

In: b.value
Out: 1

In: b = Foo.objects.create(value={1:1,2:2})

In: b.value
Out: {1: 1, 2: 2}

In: b = Foo.objects.create(value=[1,1])

In: b.value
Out: [1, 1]

仅供参考,您不能存储pass,因为它不是Python对象,而是语法的一部分.可以考虑使用None而不是通过.

FYI, you can't store pass because it is not a Python Object, but its part of syntax. Instead of pass, consider using None.

这篇关于在Django中将未知对象类型保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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