How do I set the value of a Many to Many field programmatically?

I am trying to set the value of a tag to “Bought” but I just can’t figure it out.

background :

I have created a form to buy stock and when a person buys stock I want the value of that trade to be set to “bought”, but I just can’t figure it out.

I am putting some code below (not al of it, just the part you might need)

The Bold part is where I have a problem.

the model :

class Trade(models.Model):

    trader = models.ForeignKey(User_Info, null=True, on_delete = models.SET_NULL )

    ticker = models.CharField(max_length=5, null=True)

    company_name = models.CharField(max_length=200, null=True)

    **action = models.ManyToManyField(Action)**

    price_trade_at = models.FloatField(null = True)

    stocks_bought = models.IntegerField(null=True)

    time_bought_at = models.DateTimeField(auto_now_add=True, null=True)

The Actions possible are “Bought” & “Sold”

the view :

if request.method == "POST":

        form = BuyForm(request.POST)

        if form.is_valid():

            ticker = form.cleaned_data["ticker"]

            stocks_bought = form.cleaned_data["stocks_bought"]

            t = Trade(ticker = ticker, stocks_bought = stocks_bought, **Trade.action.add("Bought")**)

            t.save()

Any help is appreciated. if you have any questions please let me know!

Thank you for your time :slight_smile:

1 Like

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)

Check out the docs here: https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/

ohhhh, I didn’t know that! Thank you.

also, what are we doing here? ------ my_action = Action(**action_kwargs)
I am a little new to this thing, please bear with me!

Also, thank you so much for the help and your time!

You’re welcome.

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:

def do_something_or_other(request, my_argument, *args, **kwargs):
    pass

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.

yep, I have seen a lot, I will definitely read up on that!

BTW, thank you for being an awesome person and helping me out, most people don’t do that!

also, you explain things really well, do you teach this, if you don’t you should totally consider it!

Have a fantastic day :slight_smile:

2 Likes

Thank you for the kind words, @VardhanMahajan. Such words can make a difference. All the best with your project!