Using Django Models across Apps

丶灬走出姿态 提交于 2020-01-25 21:20:47

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/45825885/using-django-models-across-apps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!