如何从admin中访问django模型

时间:2016-01-14 10:35:55

标签: python django

请查看以下代码
我想从管理员内部访问其他模型
在这种情况下,我想从评论应用程序admin.py中获取帖子模型的标题字段的值 谢谢

# in '<post app>'Models.py  
from site_comment.models import Comment
class post(models.Model):
    title = models.CharField(max_length=300,null=False,verbose_name='post_title')  
    comment = models.ManyToManyField(Comment,verbose_name='user comment')  
    ...  
# in '<comment app>'Models.py  
class comment(models.Model):  
    content = models.TextField(max_length=10000,blank=False,null=True,default=None)  
    post_id = models.IntegerField(null=True,default=None)  
    ...  

# in '<comment app>'admin.py  
import postapp.post  
from comment_app.models import comment
class Comment_Admin_Form(admin.ModelAdmin):  
    def get_post_title(self,request,queryset):
        return posts.objects.get(id=queryset.post_id).title
    get_post_title.short_description = 'post title'  

    model = Comment  
    list_display = ('get_post_title',)  

admin.site.register(comment,Comment_Admin_Form)

1 个答案:

答案 0 :(得分:1)

from postapp.models import posts  
from comment_app.models import comment
class Comment_Admin_Form(admin.ModelAdmin):  
    def get_post_title(self,obj):
        return posts.objects.get(id=obj.post_id).title
    get_post_title.short_description = 'post title'  

model = Comment  
list_display = ('get_post_title',)  

admin.site.register(comment,Comment_Admin_Form)