Reputation: 147
I have been able to insert data into my field which is JSONField through
modelName.family_member.append({"name":'Brian King',
"relationship":'Father',
"occupation":'Engineer'})
But I wish to add an id field which would auto increase like it does in mysql so data call would be like
{'id':1,
"name":'Brian King',
"relationship":'Father',
"occupation":'Engineer'},
{'id':2,
"name":'Demi King',
"relationship":'Mother',
"occupation":'Teacher'},
I am using Django and mysql as my database. My model declaration is like this.
family_member = models.JSONField(default=jsonfield_default_value)
Please how can I get this done
Upvotes: 0
Views: 155
Reputation: 476557
Please don't use a JSONField
. Relational databases still can not work very effectively with JSON data. It will for example prevent to efficiently update: what you here do is each time send the entire JSON blob back to the database. As the JSON grows larger, so will the amount of work by the database to update a row. Filtering, updating, removing, etc. are all quite problematic. While there has been put a lot of effort in making working with JSON more convenient, this still is quite "orthogonal" on what a relational database is supposed to do.
Usually one creates an extra model, so:
class FamilyMember(models.Model):
person = models.ForeignKey(
Person,
related_name=models.CASCADE
)
name = models.CharField(max_length=128)
relationship = models.CharField(max_length=128)
occupation = models.CharField(max_length=128)
with Person
here the model where you defined the relation originally.
You can then add data for example with:
FamilyMember.objects.create(
person=my_person,
name='Brian King',
relationship='Father',
occupation='Engineer'
)
Upvotes: 2