Can't assign to relationship in Django model

everything works well i can make an object to save product to data base and to save buyer info but look below i cant assign inside buyer which is one to one rel with product cant assign the product values it makes error why?

Hello,

when providing code for others to test/verify, please format it per:

2 Likes

ok the next tiem but i think my code in pic is very clear can u respond?

If someone wants to test your script, it is easier for them to just copy and paste … thus the reason for the formatting instructions. This is a standard Python forum protocol.

On another matter:

You need to provide the error; i.e., the traceback.

You have:

buyer=Buyer(name='alex',age='30',location='lala',phone='0900',product.product_name='bascot')

The problem is the product.product_name='bascot'.

It looks like you’re passing values to Buyer with keyword arguments, but product.product_name is not valid as a keyword name because it contains a '.'.

you can’t assign to a foreign key’s attribute this way. As stated in your other topic here you have to pass in the foreign key itself and then its attributes will be assigned automatically.
In other words, you dont pass product.product_name as an argument, but product, as in

product=Product(name='bascot')

note that you’ll probably have to define the other attributes of the Product object in that call as well

thank you so much for your response but now i got this error while running server

Ah yes you have to save the referenced foreignkey object first. In one line you may be able to do this with

product=Product.create(name='bascot')

I generally find it safer / easier / clearer to do it separately:

# create a product
product = Product(product_name='bascot')
product.save()
# create a buyer object, referring to the product
buyer=Buyer(name='alex',age='30',location='lala',phone='0900',product=product)
buyer.save()

In general, the foreign key object will already exist when you add the object that refers to it.

thank u sooooo much u made my day, last question for now if you could please? why i got always duplicates of objects in data base?

Probably because with the code you showed, for every buyer object you create a new product object.
You can just create the product object once and then refer to it in the creation of your buyer objects, by splitting up the code I showed in my second example (I added comments to hopefully make it clearer).