Arya Mz
Arya Mz

Reputation: 591

Adding many to many fields (M2M) manually in django?

I have a M2M field in my django model project. In my view I want to update a model instance with update() function. I know that for updating other ordinary fields we can pass a dictionary of the fields. But how can I pass M2M field to update() function?

Upvotes: 3

Views: 3084

Answers (2)

Vijay bang
Vijay bang

Reputation: 1

updating manytomany field you need to get instance of the sub class then apply update function.

class y:

 b = Text Field

class X:

 y = ManyToMany(y)

Code:

for y in x.y.all():
    if y: meet you condition for which row to update
       y.update(b='update')

I guess django does know support update() with M2M as it just create associate table for support and it can't understand which row in associate table to update.

Upvotes: 0

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

You can easily add relations to the ManyToManyField using the add() function (outside of your update()):

blog.entries.add(post_1, post_2 ...)

Upvotes: 5

Related Questions