Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django get attributes from foreign key's class

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!

like image 929
manosim Avatar asked Dec 16 '22 01:12

manosim


1 Answers

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.

like image 161
karthikr Avatar answered Jan 10 '23 17:01

karthikr