简体   繁体   中英

how to access to django model from within admin

Please look at the following code
i want to access from within admin to other model
in this case i want to get value of title field of post model from within comment app admin.py
thank you

# 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)
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM