Python Django how to save many to one relationship JSON data in sqlite
I was wondering how I should go about saving data items in tables which have a many to one relationship with a model
Here is the code that I got so far:
models.py:
class Recipes(models.Model):
name = models.CharField(max_length=120, default='')
pub_date = models.DateTimeField('date published')
style = models.CharField(max_length=200, default='')
brewer = models.CharField(max_length=100, default='')
type = models.CharField(max_length=20, default='All Grain')
version = models.CharField(max_length=20, default='1')
batch_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
boil_size = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
boil_time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
efficiency = models.DecimalField(decimal_places=1, max_digits=4, default=75.0)
ibu = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
abv = models.DecimalField(decimal_places=2, max_digits=4, default=0.0)
notes = models.TextField(default='')
carbonation = models.DecimalField(decimal_places=2, max_digits=4, default=0.0)
primary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
secondary_age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
age = models.DecimalField(decimal_places=1, max_digits=4, default = 0)
__fermentables = []
@classmethod
def create(cls,attr):
recipe = cls()
# do something with the book
for k in Recipes._meta.fields:
if k.name in attr:
setattr(recipe,k.name,attr[k.name])
return recipe
@classmethod
def addFermentables(self,items):
for itm in items:
self.__fermentables.append(itm)
return self.__fermentables
@classmethod
def addHops(self,items):
for i in items:
return i
class RecipeFermentable(models.Model):
recipe = models.ForeignKey(Recipes, on_delete=models.CASCADE)
name = models.CharField(max_length=200, default='')
amount = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
extract = models.DecimalField(decimal_places=1, max_digits=8, default=0.0)
type = models.CharField(max_length=20, default='')
color= models.DecimalField(decimal_places=1, max_digits=8, default=0.0)
fermentable = models.ForeignKey(Fermentable, on_delete=models.RESTRICT)
def create(cls, attr, recipes):
fermentables = cls()
# do something with the book
for k in RecipeFermentable._meta.fields:
if k.name in attr:
setattr(recipe,k.name,attr[k.name])
return fermentables
class RecipeHops(models.Model):
recipe = models.ForeignKey(Recipes, on_delete=models.CASCADE)
name = models.CharField(max_length=200, default='')
alpha = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
amount = models.DecimalField(decimal_places=2, max_digits=8, default=0.0)
use = models.CharField(max_length=10, default='')
hop = models.ForeignKey(Hop, on_delete=models.RESTRICT)
time = models.DecimalField(decimal_places=1, max_digits=4, default=0.0)
views.py:
def recipes(request):
recipes = Recipes.objects.all()
recipeFermentableFormset = formset_factory(RecipeFermentableForm, extra=1)
recipeHopFormset = formset_factory(RecipeHopForm, extra=1)
RecipeMiscFormSet= formset_factory(RecipeMiscForm, extra=1)
RecipeYeastFormSet = formset_factory(RecipeYeastForm,extra=1)
RecipeMashFormSet = formset_factory(RecipeMashForm,extra=1)
return render(request, 'recipes.html', {'recipes':recipes,"recipe_form" :RecipeForm(auto_id="recipe_%s"),
"recipe_fermentableformset":recipeFermentableFormset(prefix='fermentable'),
"recipe_hopformset":recipeHopFormset(prefix='hop'),
def saveRecipe(request):
try:
data=json.loads(request.read())
print("printing values")
print(data["name"]) #prints here works
recipe = Recipes.create(attr=data)
recipe.name = data["name"]
recipe.save()
recipe.addFermentables(items=data["fermentables"])
recipe.addHops(items=data["hops"])
return HttpResponse(serialize('json', [recipe]), content_type='application/json')
except:
return HttpResponse("error")
So basically when the user fills the forms and presses on the save button, the saveRecipe function gets called. In the function I have the recipe.save() which saves to the base Recipes table in the database.
However, I want to also save the RecipeFermentable and RecipeHops which have a many to one relationship with the Recipes model to their specific tables in the sqlite database.
And I have no idea how to go about doing this.
Could someone please help me by telling me whether the code I have so far is correct and how I should continue with saving the other data?
Thank you in advance!!
If you want to establish relationship between newly added row of "Recipe" model with existing rows of "RecipeFermentable" and "RecipeHops".Try below approach in your view function.
recipe_fermentable_obj = RecipeFermentable.objects.get(id="identifier")
recipe_hops_obj = RecipeHops.objects.get(id="identifier")
# after saving recipe into "Recipe" model.
recipe.recipefermentable_set.add(recipe_fermentable_obj)
recipe.recipehops_set.add(recipe_hops_obj)
recipe.save() # calling again
If you want to create new rows in "RecipeFermentable" and "RecipeHops" while creating new row in "Recipe" model, try below approach.
# create recipe object and save()
recipe_obj.save()
# create recipe_fermentable object with recipe obj for foreign key field.
RecipeFermentable.objects.create(recipe=recipe_obj, .....)
RecipeHops.objects.create(recipe=recipe_obj, .....)
Reference: https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/