Django: Converting an entire set of a Model's objects into a single dictionary

前端 未结 12 1291
野的像风
野的像风 2020-11-30 16:45

If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.

Is ther

12条回答
  •  时光取名叫无心
    2020-11-30 17:51

    Does this need to create an actual dict? could you get by with only something that looked like a dict?

    class DictModelAdaptor():
        def __init__(self, model):
            self.model = model
    
        def __getitem__(self, key):
            return self.model.objects.get(key=key)
    
        def __setitem__(self, key, item):
            pair = self.model()
            pair.key = key
            pair.value = item
            pair.save()
    
        def __contains__(self, key):
            ...
    

    You could then wrap a model in this way:

    modelDict = DictModelAdaptor(DictModel)
    modelDict["name"] = "Bob Jones"
    

    etc...

提交回复
热议问题