Django ForeignKey to Generic Python Data Type?
I am trying to creat开发者_StackOverflow中文版e a django model which has as one of its fields a reference to some sort of python type, which could be either a integer, string, date, or decimal.
class MyTag(models.Model):
name = models.CharField(max_length=50)
object = (what goes here??)
I know that if I want a foreign key to any other model, I can use GenericForeignKeys and content_types. How can I have a model field that references any python type? The only idea I have come up with so far is to create models that are simple wrappers on objects and use GenericForeignKeys.
Is there any way to do this?
Since you want to filter, you would need some kind of DB support for your field and json field won't be that valuable for you. You can use some different solution with different complication levels according to your actual need. One suggestion is to serialize your data to string. Pad with enough zeros for string/integer/float sorting. Now you can filter all your stuff as string (make sure you pad the value you are filtering by as well). Add a data_type column for fetching the right python object.
TYPES = [(int, 1), (Decimal, 2),(date, 3), (str, 4)]
class MyTag(models.Model):
name = models.CharField(max_length=50)
data_type = models.IntegetField(choices=TYPES)
value = models.CharField(max_length=100)
def set_the_value(self, value):
choices = dict(TYPES)
self.data_type = choices[type(value)]
if self.data_type == int:
self.value = "%010d" % value
# else... repeat for other data types
def get_the_value(self):
choices = dict([(y,x) for x,y in TYPES])
return choices[self.data_type](self.value)
(Disclaimer: this is a hack, but probably not the worst one).
JSONField
would work, but it won't handle Decimal
as is.
If you don't need to filter through this field you could either use JsonField or you could pickle your objects like this
The second aproach would allow you to store nearly any type of python data type, though it would be usable only from python code.
If you need to filter through this data you should just create separate fields with one data type.
精彩评论