[Fixed]-Django ManyToManyField not saving in admin

0πŸ‘

βœ…

So, as far as I understand, the ManyToManyField in the Section class doesn’t actually save any DocumentType data in the Section database table, rather it saves the relationship to DocumentType.
Therefore if I want to access the document_type of a section I have to look up the Section objects via the DocumentType object, and vice versa.

For instance:

>>> DocumentType.objects.get(name="WAN").section_set.all()
[<Section: ALL 1>, <Section: ALL 2>, <Section: WAN 5>, <Section: WAN 6>]
>>> DocumentType.objects.get(name="Campus LAN").section_set.all()
[<Section: ALL 1>, <Section: ALL 2>, <Section: Campus LAN 3>, <Section: Campus LAN 4>]

or:

>>> Section.objects.filter(document_type_s__name="WAN")
[<Section: ALL 1>, <Section: ALL 2>, <Section: WAN 5>, <Section: WAN 6>]

or:

>>> DocumentType.objects.filter(section__name__startswith="Campus")
[<DocumentType: Campus LAN>, <DocumentType: Campus LAN>]

Although this:

>>> DocumentType.objects.filter(section__document_type_s="WAN")

raises ValueError: invalid literal for int() with base 10: 'WAN' because there is no data under the section_document_type m2m field, only the relationship. So this is still the case:

>>> original_sections = Section.objects.all()
>>> for a in original_sections:
...     print a.document_type_s
... 
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None
lld.DocumentType.None

Further info here.

1πŸ‘

How do you think this is going to work?

Section(document_type_s="Campus LAN", name="Fake", original=True)

document_type_s is a ManyToMany field but you are passing in a string value

Read the docs for ManyToMany:
https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_many/

For many to many relation to be created the Section instance already has to exist (because in the db a m2m relation is an extra table with two foreign keys)… so you need to:

dt = DocumentType.objects.get(pk=1)
section = Section.objects.create(name="Fake", original=True)
section.document_type_s.add(dt)
πŸ‘€Anentropic

Leave a comment