0

I have defined optional variables in my django model. In my view, I might have those values or they might be None. I want to create that object without worrying about sending a None argument to the django model.

For example, Book object has a title, but publisher is optional.

right now in my view I'm doing something like

if publisher is None:
    Book.objects.create(title=title)
else:
    Book.objects.create(title=title, publisher=publisher)

Now this isn't manageable if there are multiple optional fields. What's the solution?

Kiarash
  • 6,588
  • 9
  • 41
  • 68

3 Answers3

0

How about using ** operator:

attrs = {'title': title}
if publisher is not None:
    attrs['publisher'] = publisher
Book.objects.create(**attrs)

UPDATE alternative - using Model.save:

book = Book(title='title')
if publisher is not None:
    book.publisher = publisher
book.save()
falsetru
  • 336,967
  • 57
  • 673
  • 597
0

Take a look at this:

Call a function with argument list in python

Basically create an array like args and then pass it in as *args to the method required.

You can also do something similar with **kwargs. Take a look at this:

Passing a list of kwargs?

Community
  • 1
  • 1
KVISH
  • 12,511
  • 15
  • 83
  • 157
0

Branching off the other answers... try this

def make_book(**kwargs):
    query = {key: value for key, value in kwargs.items() if value}
    Book.objects.create(**query)

I suggest declaring this as a method on your models manager so that you can quickly make instances where ever you need them like

Book.objects.make_book(title="The Title",publisher=None)
Michael Giba
  • 120
  • 4