[Answer]-Django how to create an object with the dictionary with m2m data

1👍

You can assign a list of IDs to the M2M field. Related manager will convert this list to valid Subject objects:

book = Book.objects.create(title=dictionary['title'],
                           subtitle=dictionary['subtitle'])
book.subjects = dictionary['subjects']

If you want to “deserialize” the model from such dictionary then you can do something like this:

def create_obj(klass, dictionary):
    obj = klass()

    # set regular fields
    for field, value in dictionary.iteritems():
        if not isinstance(value, list):
            setattr(obj, field, value)

    obj.save()

    # set M2M fields
    for field, value in dictionary.iteritems():
        if isinstance(value, list):
            setattr(obj, field, value)

    return obj

book = create_obj(Book, dictionary)

0👍

book = Book()
book.title = dictionary['title']
book.subtitle = dictionary['subtitle']
book.subjects = dictionary['subjects']
book.save()

Leave a comment