Brian
Brian

Reputation: 7654

ManyToManyField.add has no effect

I have two models, one of which (Bar) has two M2M relations pointing to Foo.

class Foo(Model):
    pass  # Whatever

class Bar(Model):
    foos = ManyToManyField(
        Foo, blank=True, related_name="+")
    bazs = ManyToManyField(
        Foo, blank=True, related_name="+")

After setting up a project using Django 1.8, none of these fields have working .add() methods, as demonstated below.

In [1]: foo = Foo.objects.first()
Out[2]: <Foo: ...>

In [3]: bar = Bar.objects.first()
Out[4]: <Bar: ...>

In [8]: bar.foos.add(foo)

In [9]: bar.foos.all()
Out[9]: []

In [11]: bar.save()

In [12]: bar.foos.all()
Out[12]: []

The documentation for ManyToManyField is here.

The documentation for related_name is here. It is used because the reverse related_names for Bar would otherwise conflict on Foo.

What is the suggested workaround?

Upvotes: 1

Views: 250

Answers (1)

prawg
prawg

Reputation: 511

I agree with Gocht that it most likely has something to do with the related_name attributes having the same value. Based on your comment it seems you are looking for the ForeignKey field rather than the ManyToManyField. If you only want a 1 way relationship from Bar to Foo that would be the best choice.

Was there another reason you didn't use that type of field?

Not enough points to comment on your comment otherwise I would put this there. :(

Upvotes: 1

Related Questions