开发者

Which type of field should I choose to store array list of IDs in django models?

Which type of field should I choose to store ar开发者_开发百科ray list of IDs in django models? I want to easily check the existence?


I'll go on record to say that I think it's likely that you're approaching your base problem the wrong way. That said, here's code for a custom field that will effectively store a set of IDs:

class SetField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def get_prep_value(self, value):
        if value is None:
            return json.dumps([])
        return json.dumps(list(value))

    def to_python(self, value):
        if isinstance(value, set):
            return value
        if not value:
            return set()
        return set(json.loads(value))


Here is one way to do it. There's many other ways though.

ids = ['1', '2', '3',]

for id in ids:
    try:
        Model.objects.get(pk=id)
    except Model.DoesNotExist:
        print "ID: %s doesn't exist" % id


Store it as an IntegerField(primary_key=true) in models.py and when you want to check for certain rows, silent1mezzo's try:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜