Mukul
Mukul

Reputation: 81

How to store list in Django model field while using SQLite

I'm stuck with the issue that I need to insert the list [ ] in the model field while using SQLite,

Group_Model.py:

class ClassificationGroup(models.Model):
   vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True)
   id = models.IntegerField(primary_key=True)
   name = models.CharField(max_length=100)
   description = models.CharField(max_length=1000)
   classification_id = models. [what do i take here to make it capable to store list of ids that will be related to the classification table.]

Classification_Model.py

class Classification(models.Model):
   id = models.IntegerField()
   name = models.CharField(max_length=100)
   description = models. CharField(max_length=1000)
   domain_name = models.CharField(max_length=200)

i just want to store the list of classification in the one field of the Classification Group Mentioned above, Please help me out in this.

Upvotes: 0

Views: 2875

Answers (1)

enes islam
enes islam

Reputation: 1120

Add a method to your class to convert it automatically.

import json


class ClassificationGroup(models.Model):
    #...
    classification_id = models.CharField(max_length=200)

    def set_classification_id (self, lst):
        self.classification_id = json.dumps(lst)

    def get_classification_id (self):
        return json.loads(self.classification_id)

your view:

obj = ClassificationGroup.objects.create(name="name",**data)
obj.set_classification_id([1,2,3])
obj.save()
#there are several examples of using this method

your HTML:

{% for obj in objects %}
 {{ obj.name }}
 {{ obj.get_classification_id }}
{% endfor %}

Upvotes: 1

Related Questions