Home > Software design >  Djnago Adding ManytoMany objects to an object after being created
Djnago Adding ManytoMany objects to an object after being created

Time:04-12

Im trying to add a many to many field to an object after it is created but keep running into the same error: Direct assignment to the forward side of a many-to-many set is prohibited. Use dogs.set() instead.

in my models.py

class linkedDog(models.Model):
    linked_dog = models.ForeignKey(Dog, blank=True, null=True, on_delete=models.CASCADE)
    service_chosen = models.ManyToManyField(Service, blank=True)
    shampoos_chosen = models.ManyToManyField(Shampoo, blank=True)
    total_time = models.IntegerField(blank=True, default=0)


class PsuedoAppointment(models.Model):
    client = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)
    dogs = models.ManyToManyField(linkedDog, blank=True)
    total_time = models.IntegerField(blank=False, default=0)

I am trying to add a linkedDog object to dogs field in my views I've used this question as a reference

Direct assignment to the forward side of a many-to-many set is prohibited. Use emails_for_help.set() instead

But can't figure out what I'm doing differently or where its going wrong

@login_required
def loggedin_appointment_view(request):
    if request.method == "POST":
        form = linkedDogForm(request.POST, user=request.user)
        if form.is_valid():
            dog = form.save()
            dog_id = dog.id
            dogsquery = linkedDog.objects.filter(id=dog_id)

            appointment = PsuedoAppointment.objects.create(client=request.user, dogs=None, total_time=None)

            for dog in dogsquery:
                appointment.dogs.add(dog)
            
            return render(request, 'home.html')
    
    else:
        dog_form = linkedDogForm(user=request.user)
        return render(request, "appointment_template/loggedin_appointmentmaker.html", context={'dog_form' : dog_form})

I also tried

            dog = form.save()
            dog_id = dog.id
            dogsquery = linkedDog.objects.filter(id=dog_id)
            appointment = PsuedoAppointment.objects.create(client=request.user, dogs=None, total_time=None)

            appointment.dogs.set(dogsquery)

CodePudding user response:

You should remove the dogs=None. Furthermore total_time can not be None, since it is a non-NULLable field, you can set this to 0 for or omit it from the .create(…) call [Django-doc]:

appointment = PsuedoAppointment.objects.create(
    client=request.user  # no dogs=None
)
for dog in dogsquery:
    appointment.dogs.add(dog)
  • Related