wrufesh
wrufesh

Reputation: 1406

django how to create an object with the dictionary with m2m data

My model:

class Book(models.Model):
    title = models.CharField(max_length=254)
    subtitle = models.CharField(max_length=254, null=True, blank=True)
    subjects = models.ManyToManyField(Subject)

class Subject(models.Model):
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=254, null=True, blank=True)

i have a dictionary like this:

dictionary = {'title':'test', 'subtitle':'test subtitle', 'subjects':[1,6]}

how can i create a book model programetically with fields data in dictionary.

def create_obj(class, dictionary):
    pass

Upvotes: 0

Views: 2000

Answers (2)

Unubold Yura
Unubold Yura

Reputation: 11

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

Upvotes: 0

catavaran
catavaran

Reputation: 45575

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)

Upvotes: 1

Related Questions