visible = models.BooleanField()
owner = models.ForeignKey(User, null=True)
def update_address(**kwargs):
address = Address.objects.get(address=kwargs.get('address'))
try:
address.visible = kwargs.get('visible')
except:
pass
try:
address.owner = kwargs.get('owner')
except:
pass
update_address()
should result in nothing happening to address.visible
or address.owner
.
update_address(owner=None)
should delete whatever existing owner object was set.
The thing that's confusing me is how to tell if owner=None
was explicitly set so I know to delete the existing owner object, or if it was called without owner
set to anything so I should leave the owner as it is.
you can use the "in" keyword to check if the key is there or you can specify the default param in the second argument of the dict.get(key, default) function
if 'visible' in kwargs:
do something
# OR
visible = kwargs.get('visible', False)
Update:
if your super() class (ie the parent model) doesn't take the visible param, you can use the dict.pop(key, default) to extract the param before passing it to the super. I thought this could be useful for you to know as well.
def __init__(self, *args, **kwargs):
visible = kwargs.pop('visible', False)
super().__init__(*args, **kwargs)
You could use in
and keys
:
if 'visible' in kwargs.keys():
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With