5

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!

manosim
  • 3,630
  • 12
  • 45
  • 68

1 Answers1

12

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.

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 1
    Wow! It was really simple!! Thanks a lot for your answer! Got lost with all those topics and I thought I should use filter. Thanks again!! – manosim Feb 14 '14 at 04:11
  • One last question about this. Is it possible to use "getdegree" to filter the results using "list_filter"? Because when I add it to "list_filter", I'm getting errors. – manosim Feb 14 '14 at 04:17
  • See this: http://stackoverflow.com/questions/991926/custom-filter-in-django-admin-on-django-1-3-or-below – karthikr Feb 14 '14 at 04:18