A
A
asmodeus13th2021-05-26 11:10:37
Django
asmodeus13th, 2021-05-26 11:10:37

How to automatically bind order model to User?

Have a nice day! I have models: custom user (Account) and order (Order). When a user creates an order, the latter should automatically be added to the user's database. For those who do not understand what kind of connections we are talking about: https://djbook.ru/rel1.9/ref/models/fields.html

Work logic:
I, the user, register on the site (Account model). Now I have a profile page. I select a product, add it to the cart (Cart model) and confirm the order. Now the order is in the database (Order model).
What needs to be added:
An order (Order model) should appear on the profile page (Account model).

How I solved:
added a ManyToManyField(Order) relationship to the Account model. Now, having created an order, I can connect it to the user (via the admin panel).
But! I don't want to do it manually. Is there a way to automatically highlight the order in the Account model when creating an order?
I think I was able to correctly convey the idea. For example, there are analogies:
1. when creating a blog post, the author is the user who writes this post;
2. when creating a comment in an article, the author is the user who writes this comment, etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2021-05-26
@asmodeus13th

Why do you need a MANyToMany connection here? Can one order have several users?)
You need a simple OneToMany relationship. In the Order model, create a field account = fireld.ForeignKey(Account, related_name='accounts_order') , and you will write the Account object to it when ordering.
Next on the profile page output account_obj.accounts_order.all()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question