0

I have an M2M relationship like this:

class Foo:
    # foo fields...

class Bar:
    Foos = ManytoManyField(Foo)

I am trying to add a foo to the list of foos attributed to a Bar, so here's what I have:

    if Foo not in Bar.Foos:
        Bar.Foos.add(Foo)

Question: is the if-judgment really necessary?

Thanks

Exis Zhang
  • 502
  • 6
  • 10

1 Answers1

0

As stated in the Django docs : https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_many/

Adding a second time is OK, it will not duplicate the relation

You may call bar.foo.add(baz) many times, it won't create a duplicate relationship or line in database.

p.s.: in Python, everything (variables, instances, etc..) must be lowercase with words separated by underscores. The exceptions are ClassNames, ExceptionNames and GLOBAL_CONSTANT_NAMES. C.f.: What is the naming convention in Python for variable and function names?

Exemple with your above code :

class Bar:
    foos = ManytoManyField(Foo)

def your_view(id):
    foo = Foo.objects.get(id=id)
    bar = Bar.objects.get(foo=foo)

    if foo not in bar.foos:
        bar.foos.add(foo)    
pmhoudry
  • 36
  • 4