gamer
gamer

Reputation: 613

having trouble in saving form data into ManyToMany field

My Model is like

class Dish(models.Model):
    names = models.ManyToManyField(DishName)
    restaurant = models.ManyToManyField(Restaurant)

And My view file is like

  def AddDish(request):
        if request.method == 'POST':
            dishname = request.POST.get('name')
            res = request.POST.get('restaurant')
            restaurant = Restaurant.objects.get(id=res)


            r = Dish(generic_name=GenericName,
                       names=dishname,
                       restaurant=restaurant,
                           )
            r.save()

And when I try to add my values to Dish model this error occue

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

I tried to use set but Didnt get where to use this like I tried restaurant.set(r) but no luck till now . Any help would be highly appreciated . thanks in advance

Upvotes: 0

Views: 40

Answers (2)

Waket Zheng
Waket Zheng

Reputation: 6331

If you want to use .set ==>

def AddDish(request):
    if request.method == 'POST':
        dishname = request.POST.get('name')
        res_id = request.POST.get('restaurant')
        restaurant = Restaurant.objects.get(id=res_id)
        dn = DishName.objects.get(name=dishname)
        dish = Dish.objects.create(generic_name=GenericName)
        dish.names.set([dn])
        dish.restaurant.set([restaurant])
        dish.save()

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

def AddDish(request):
    if request.method == 'POST':
        dishname = request.POST.get('name')
        res = request.POST.get('restaurant')
        restaurant = Restaurant.objects.get(id=res)
        dn = DishName(name=dishname)
        r = Dish.objects.create()
        r.restaurant.add(restaurant)
        r.names.add(dn)

I'm however not convinced that you here should use a ManyToManyField in the first place. If a dish only belongs to one Restaurant, then you probably should use a ForeignKey.

You thu first need to save your Dish before you can alter the ManyToMany relations, since otherwise, your Dish has no primary key assigned to it.

Upvotes: 1

Related Questions