Django Form, сохранение в несколько таблиц

Я работаю над системой ввода заказов, в которой будут отслеживаться продукты, рецепты и заказы для клиентов. Я пытаюсь понять, как создать форму/шаблон recipe_ingredient, которая будет создавать запись о продукте, запись о рецепте и связанную запись(и) с ингредиентами рецепта, когда пользователь создает новый рецепт. Форма должна запрашивать название рецепта, описание, а также ингредиенты (таблица продуктов) и процентное содержание.

Проектирование базы данных (не знаю, правильно ли я указал символы) enter image description here

Вот мой models.py для ингредиента product/recipe/recipe

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    sku = models.CharField(max_length=200, null=True, blank=True)
    supplier = models.ForeignKey(Supplier, null=True, on_delete= models.SET_NULL)
    description = models.CharField(max_length=200, null=True, blank=True)
    cost_per_pound = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
    cost_per_ounce = models.DecimalField(max_digits=7, decimal_places=2, blank=True)
    note = models.CharField(max_length=1000, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

class Recipe(models.Model):
    name = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
    description = models.CharField(max_length=200, null=True, blank=True)

class Recipe_Ingredient(models.Model):
    recipe_name = models.ForeignKey(Recipe, null=True, on_delete=models.SET_NULL)
    ingredient = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
    recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True)

У меня есть полурабочая форма ингредиентов рецепта, но пользователю нужно сначала создать продукт, а затем выбрать его при создании рецепта и ингредиентов рецепта.

def recipeCreate(request):
    RecipeIngredientFormSet = forms.inlineformset_factory(Recipe, Recipe_Ingredient, form=RecipeIngredientForm, extra=10, fields=('ingredient', 'recipe_percent',))
    form = RecipeForm()
    formset = RecipeIngredientFormSet()
    if request.method == 'POST':
        form = RecipeForm(request.POST)
        if form.is_valid():
            recipe = form.save()
            formset = RecipeIngredientFormSet(request.POST, instance=recipe)
            if formset.is_valid():
                formset.save()
            return redirect('/')
    context = {'form':form, 'formset':formset}
    return render(request, 'accounts/recipe_form.html', context)

Вот что я пытаюсь отобразить для конечного пользователя... enter image description here Когда они создают рецепт, появляется эта форма. Они вводят название, описание, ингредиенты и процентное соотношение. Когда они нажимают "Отправить", я хочу, чтобы произошло следующее

  1. the name supplied, will create a new entry in the PRODUCT table w/ a default supplier of "8" (supplier FK), everything else blank
  2. create an entry in the RECIPE table with the name and description entered
  3. create the entries to the RECIPE_INGREDIENTS table with the information supplied

Я знаю, что мне нужно удалить FK-отношение от PRODUCT к RECIPE.... Думаю, когда я пойму, как сохранить форму в нескольких таблицах, я смогу понять, как перепроектировать базу данных.

Вернуться на верх