What is the most efficient way to store a list in the Django models?

后端 未结 12 870
执笔经年
执笔经年 2020-11-28 01:27

Currently I have a lot of python objects in my code similar to the following:

class MyClass():
  def __init__(self, name, friends):
      self.myName = name
         


        
12条回答
  •  清酒与你
    2020-11-28 01:57

    Storing a list of strings in Django model:

    class Bar(models.Model):
        foo = models.TextField(blank=True)
    
        def set_list(self, element):
            if self.foo:
                self.foo = self.foo + "," + element
            else:
                self.foo = element
    
        def get_list(self):
            if self.foo:
                return self.foo.split(",")
            else:
                None
    

    and you can call it like this:

    bars = Bar()
    bars.set_list("str1")
    bars.set_list("str2")
    list = bars.get_list()
    if list is not None:
        for bar in list:
            print bar
    else:
        print "List is empty."      
    

提交回复
热议问题