Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Django Models across Apps

Good afternoon,

I have seen similar questions but none of the answers really resonate with me. I am new to django development and am trying to get use to the models. My question is how do I utilize a model from one app in another appropriately?

For instance, I have a project, Project 1 that consists of the a Person app that manages the users profile. This app has the model for a person, but then that person is used in Activities for the activities they have completed, and another progress in a game. All of these apps need the person to be the key.

I am not understanding how to make these relate.

Thanks for your help as I become django-ified.

like image 641
Bring Coffee Bring Beer Avatar asked Jan 03 '23 13:01

Bring Coffee Bring Beer


1 Answers

Just by importing model to other apps:

from person.models import Person

and then you can any relevant thing with model Person, for example:

class Activity(models.Model):
    person = models.ForeignKey(Person)

Make sure that you imported model Person in the file before using it. You can also do something like this:

from person.models import Person

def list(request):
    person_list = Person.objects.all()

I hope you got idea of how to use one app model in another app in django.

Either you want to use app_1 model to app_2 models.py or views.py or somewhere else, just import that model and use it as per your requirement in your application.

like image 57
Piyush Maurya Avatar answered Jan 07 '23 03:01

Piyush Maurya