Search code examples
djangodatabasemany-to-manyrelationshipdata-modeling

django and DB modeling: I think I've got Many to Many wrong


I have an object Option which is like a type, it only has a property: name (it could have more properties in the future). Instances of Option have a unique name.

Many objects may have zero or more of Option instances.

For example:

class Consumer:
    options = models.ManyToManyField(Option, blank=True, help_text="the options")

But then, in order to create the Option instances for Consumer's many-to-many options relationship, I need to create a new Option instance and add it to options.

This however "breaks" my uniqueness: Now I have two with the same name! And so forth for every instance of Option I create.for Many-to-Many links. Instead of the 4 I need, I have now 68 in my DB...

I believe I have fundamentally misunderstood Many-To-Many, and / or mis-designed this relationship...

Can anybody help?

EDIT: Here's how I set options in an example:

def enable_option(request, pk=0, option_pk=0, *args, **kwargs):
    consumer = get_object_or_404(Consumer, pk=pk)
    option = get_object_or_404(Option, pk=option_pk)

    new_option = Option()
    new_option.name = option.name // I know I am breaking my own rule...but when I read the consumer options, I need the exact same name! Still, I believe I am modeling wrong
    new_option.save()
    consumer.options.add(new_option)
    consumer.save()

    return HttpResponse()

Solution

  • I don't really understand why you create a new Option here. You get the existing one; you can just add that to the relationship:

    consumer = get_object_or_404(Consumer, pk=pk)
    option = get_object_or_404(Option, pk=option_pk)
    consumer.options.add(option)
    

    You don't even need to call save, as modifying an m2m does not change the instance itself.