Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show foreignkey attributes django admin fields?

Tags:

python

django

This question is similar with others but it is a different one actually ! So, I have 3 models such as (I have deleted some unnecessary things for shorter code):

class Category(models.Model):
    category_title = models.CharField(max_length=200)
    category_content = models.TextField()
    category_slug = models.CharField(max_length=200)

     def __str__(self):
         return self.category_title


class Classes(models.Model):
    classes_title = models.CharField(max_length=200)
    classes_content = models.TextField()
    classes_category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT)

     def __str__(self):
         return self.classes_title

class Subjects(models.Model):
    subject_title = models.CharField(max_length=200)
    subject_content = models.TextField()
    subject_class = models.ForeignKey(Classes, on_delete=models.SET_DEFAULT)

    def __str__(self):
         return self.subject_title

So let me give an example. I can have 2 categories and in those categories I can have "same named" classes. Lets think about maths is a class for both categories. When I want to add a new subject to maths I see 2 same named maths in admin page. So I want to know which one belongs to which category in admin page. So I can add my subject to right class.

class SubjectAdmin(admin.ModelAdmin):

    fields = ('subject_title', 'subject_content', 'subject_class',)

So in this picture (Subjects = Konular) I am adding a new subject. I will have a foreign key to Class. However I have same name for classes that are coming from different categories. So in this dropdown how can I know which class belongs to which category ?

enter image description here

like image 296
omerS Avatar asked Sep 20 '25 06:09

omerS


1 Answers

Try this...

class KonularAdmin(admin.ModelAdmin):

    fields = ('subject_title', 'subject_content', 'subject_class', 'get_classes_category_title')

    def get_classes_category_title(self, obj):
         subject_object = Subjects.objects.get(id=obj.subject_class)
         return str(subject_object.classes_category.category_title)

  • It returns the category title name
like image 135
Ashish Sondagar Avatar answered Sep 22 '25 20:09

Ashish Sondagar