Django, Models, and Apps
I'm new to Django and MVT, so I apologize if this is a silly question. I've looked over some similar questions but am looking for a little additional clarity and whether I'm even attempting to do the right thing.
Here's a simplified version of what I'm working on. Let's say I'm designing a Django interface to a pre-existing database. The database is old and other systems add data to it. The Django interface will be read only. Simple structure with 4 content tables:
- Widgets
- Creators (for simplicity, each Widget has one Creator)
- Customers
- Orders (customer many-to-many orders, orders many-to-many widgets)
I started by creating a Django app called "Wid开发者_如何转开发get" that displays Widget information, and creating models for all of the tables in the database. This works great, with an url like /widget/1234 I get the information for Widget with id 1234, info from the Creator table, and how many times it has been ordered.
Now I wanted to create an app called "Customer" that displays information for customers (data from Customer table, orders placed, widgets ordered, etc).
Am I doing the wrong thing? Should there be a separate "Customer" app?
If it does indeed make sense for there to be a separate "Customer" app, what do I do about the models? They are identical to the models used in the "Widget" app as they are dealing with the same tables in the same database. Do I just import from the other app? Thanks!
No, you do not need to create a separate app for each model. You should create an application for each distinct set of functionality in your project. Since you're just learning, you should create one application (with the name of your project) and use that to learn.
As for the models, they are just a representation layer of the tables in your db that makes it easy and handles a lot of the heavy lifting associated with interacting with your db. So in your case you would create a model for each table in your existing db: Widget, Creator (you may want to consider making this a foreign key link to your User table), Customer, Order.
The way you return specific data is through your views. So for example to get all the data for a specific widget using the url in your example, the url /widget/1234 would point to a function on your views.py page where you would query your db for the information you need, and send it to your template. In your example the query would look something like:
widget = Widget.objects.get(id=1234)
Note that since you have an existing database you will have to override Django's default db naming conventions. You can read more about how to do that here: https://docs.djangoproject.com/en/dev/topics/db/models/
However the best advice I can give you would be to put your own project/app aside for a couple of days and go through the official Django tutorial and documentation. Especially when you're first learning, its incredibly well documented and easy to learn:
https://docs.djangoproject.com/en/dev/
精彩评论