简体   繁体   中英

How to exchange data between apps in Django using the database?

I'm using Django to work on a web. I have created 2 apps: One for the clients to register, and add their data to the database, and a second app for users to access and see the interactive interface. The idea is to use the second app to get data from the clients in the database, and use it to show some information to the user.

My problem is that i don't understand how to make the second app to get the information from the database. Do i need to create the same models from the first app on model.py on the second one? Or how do i make the second app to use a Queryset to retrieve data from the database?

I don't know if is necesary to say that i'm using a MySql database.

You do not need to define the same models twice. In fact, you shouldn't for a number of reasons, like that the data should live in one place in your db (the table names get generated based on app name and model from migrations), and you should not repeat code (DRY).

You define the models in the application that they should belong (this is entirely a design decision). The migrations are created for the appropriate application.

Then, in the second application, you simply import the model that you wish to use from the first application and construct any query you like. Example:

app1/models.py

from django.db import models

class Node(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField(blank=True)

app2/views.py

from django.views.generic.detail import DetailView
from app1.models import Node

class NodeView(DetailView):
    model = Node
    template_name = 'app2/index.html'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM