Django从外键类获取属性 [英] Django get attributes from foreign key's class

查看:56
本文介绍了Django从外键类获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想展示另一类的一个属性.当前类具有要在其中获取属性的类的外键.

I would like to show one attribute from another class. The current class has a foreign key to class where I want to get the attribute.

# models.py
class Course(models.Model):
    name = models.CharField(max_length=100)
    degree = models.CharField(max_length=15)
    university = models.ForeignKey(University)

    def __unicode__(self):
        return self.name

class Module(models.Model):
    code = models.CharField(max_length=10)
    course = models.ForeignKey(Course)

    def __unicode__(self):
        return self.code

    def getdegree(self):
        return Course.objects.filter(degree=self)

# admin.py.
class ModuleAdmin(admin.ModelAdmin):
    list_display = ('code','course','getdegree')
    search_fields = ['name','code']
    admin.site.register(Module,ModuleAdmin)

所以我想做的就是使用"getdegree"来获取模块具有的学位".我在这里阅读了几个主题,还尝试了django文档,但是我不是一个有经验的用户,所以即使我猜它很简单,我也无法弄清楚.谢谢!

So what i'm trying to do is to get the "degree" that a module has using the "getdegree". I read several topics here and also tried the django documentation but i'm not an experienced user so even I guess it's something simple, I can't figure it out. Thanks!

推荐答案

这很简单.

尝试一下:

def getdegree(self):
    return self.course.degree

此处的文档

您可以安全地执行此操作,因为 course 不是可为空的字段.如果是这样,则应该在访问对象的属性之前检查对象是否存在.

You can do this safely because course is not a nullable field. If it were, you should have checked for existence of object before accessing its attribute.

这篇关于Django从外键类获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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