Before the action can be linked to the trade, an instance of trade must first exist. You cannot instantiate a model object with a many-to-many argument (please double check the docs for the details)
# create an action
my_action = Action(**action_kwargs)
my_action.save()
# you can also fetch an action instead of instantiating one.
my_action = Action.objects.get(id=1)
# create a trade
trade = Trade(ticker=ticker, stocks_bought=stocks_bought)
trade.save() # you must save the object before you can add items to the many-to-many relationship
trade.action.add(my_action)
In Python you can unpack a dictionary. For example, let’s say you had a model and wanted to create a new instance of it.
# an example Django model
class Trade(models.Model):
price = models.DecimalField()
qty = models.IntegerField()
# we can instantiate the model like this
trade = Trade(price=1.00, qty=3)
trade.save()
# we can also use a dictionary and unpack it into the constructor
unpack_me = {"price": 1.00, "qty": 3}
trade = Trade(**unpack_me) # ** unpacks a dictionary into key, value pairs, i.e. price=1, qty=3
trade.save()
Both the pieces of code result in the same outcome, just done in slightly different ways.
You’ll often see, especially in Django, methods that look something like this:
The **kwargs argument allows any number of key, value pairs to be passed into the function as long as the are passed in last. I would recommend reading up and *args and **kwargs in Python as they come in quite handy in Django.