Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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.

like image 698
Efraín Avatar asked Feb 23 '17 19:02

Efraín


Video Answer


1 Answers

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'
like image 125
Wtower Avatar answered Sep 19 '22 23:09

Wtower