Django get attributes from foreign key's class

2019-06-14 10:32发布

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)

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!

1条回答
霸刀☆藐视天下
2楼-- · 2019-06-14 10:47

It is pretty straight forward.

Try this:

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

Documentation here

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.

查看更多
登录 后发表回答