Django:如何使用其他应用程序中的模型 [英] Django : How to use models from another app

查看:206
本文介绍了Django:如何使用其他应用程序中的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个应用程序:主页博客。我在应用程序博客中有一个模型 Post 。我可以将此模型用于应用程序博客,但不能用于应用程序主页

I have got two apps: homepage and blog. I have a model Post in the app blog. I can use this model for the app blog but not for the app homepage.

如何在应用程序主页中使用此模型:我想将一些最近的博客文章显示为主页中的链接。

How can I use this model in app homepage: I want to display some of my recent blog posts as links in my homepage.

blog / models.py

blog/models.py

from django.db import models
from django.db.models import permalink

class Post(models.Model):
    title=models.CharField(max_length=140)
    body=models.TextField()
    date=models.DateTimeField()

    def __str__(self):
        return self.title

blog / urls.py

blog/urls.py

from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from blog.models import Post     
from . import views
urlpatterns = [ 
    url(r'^$', ListView.as_view(
        queryset=Post.objects.all().order_by("-date")[:25],
        template_name="blog/blog.php")),
]

这就是我在应用程序 blog 模板

This is how I displayed my recent blog post in app blog Template

{% for post in object_list %}
     <div id="post_list">
     <h2 class="header1"><a href="/blog/{{post.id}}">  {{ post.title }}</a></h2>
     <h5 class="date_time">{{ post.date }}</h5>
     {{ post.PostImage|safe }}
    <br>        
    <div id="button"><a href="/blog/{{post.id}}"><text class="buttonDefault" > READ POST </text></a></div>
    </div>
{% endfor %}

我想在首页模板中类似地显示它。

I want to display it similarly in homepage template.

推荐答案

您可以通过导入其他应用程序中的模型,方法与导入永久链接来自Django模型:

You can use models from other apps by importing them the same way you imported permalink from the Django models:

from django.db.models import permalink

在不知道项目结构的情况下很难告诉您确切的导入信息。可能是这样的:

It's difficult to tell you the exact import without knowing your project structure. It could be something like this:

from project.apps.blog.models import Post

为了使生活更轻松,您可以使用像样的IDE为您解决进口问题(例如PyCharm)。

To make your life easier you could use a decent IDE that resolves imports for you (like PyCharm for example).

这篇关于Django:如何使用其他应用程序中的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆