djangodjango-modelsdjango-formsmanytomanyfield

Django how the link ManytoManyField data with FloatField data?


I have manytomanyfield inside my model.The manytomanyfield field lists the products in the products table. I want to enter the amount for each product I choose. How can I relate manytomanyfield to floatfield field?

That's my model:

`

class TaskSources(models.Model):
    id = models.AutoField(primary_key=True)
    user_task_id = models.ForeignKey(UserTask,on_delete=models.CASCADE)
    product_id = models.ManyToManyField(Product, verbose_name="Product",default=None)
    product_amount = models.FloatField(max_length=255,verbose_name="Product Amount")

`

The form:

`

class TaskSourcesForm(forms.ModelForm):
    class Meta:
        model = TaskSources
        fields = ['product_id', 'product_amount']

`

The views:

`

@login_required(login_url="login")
def addUserTask(request):
    user_task_form = UserTaskForm(request.POST or None,initial={'user_id': request.user})
    task_sources_form = TaskSourcesForm(request.POST or None)

    if request.method == 'POST':
        if user_task_form.is_valid():
            user_task = user_task_form.save(commit=False)
            user_task.author = request.user
            user_task.save()
            print(user_task.id)
            if task_sources_form.is_valid():
                task_sources = task_sources_form.save(commit=False)
                task_sources.user_task_id = UserTask(id = user_task.id)
                task_sources.save()
                task_sources_form.save_m2m()

            messages.success(request,"Task added successfully!")
        return redirect(".")

    context = {
        "user_task_form" : user_task_form,
        "task_sources_form" : task_sources_form,
    }

    return render(request,"user/addtask.html",context)

`

Thanks for care.

enter image description here

I tried associating the two fields with each other, but I could not succeed.


Solution

  • If I got it right I think that what you need is an intermediate table between your models. That way you can link an amount of a product to a TaskSource, something similar to this:

    class Product(models.Model):
        name = models.CharField(max_length=128)
    
        def __str__(self):
            return self.name
    
    class ProductAmount(models.Model):
        amount = models.FloatField(max_length=255,verbose_name="Product Amount")
        product = models.ManyToManyField(Product, through='TaskSources')
    
        def __str__(self):
            return self.name
    
    class UserTask(models.Model):
        name = models.CharField(max_length=128)
    
        def __str__(self):
            return self.name
        
    class TaskSources(models.Model):
        id = models.AutoField(primary_key=True) # this is not really necessary
        task = models.ForeignKey(UserTask,on_delete=models.CASCADE)
        product_amount = models.ForeignKey(ProductAmount, on_delete=models.CASCADE)