Jurudocs
Jurudocs

Reputation: 9175

How to get Django Admin to display a field connected with a foreign key?

How to get Django display the foreign key of AnotherAim.aimid.code into one tabel of AnotherAimAdmin in the backend?

This is a classical Admin "view" separated by two different tabels in the backend:

class AimAdmin(admin.ModelAdmin):
    list_display = ('code')

# AnotherAim and AIM are connected via a foreight key

class AnotherAimAdmin(admin.ModelAdmin):
    list_display = ('name','sur_name', 'email')
    search_fields = ['name','sur_name']


admin.site.register(Aim,AimAdmin)
admin.site.register(AnotherAim, AnotherAimAdmin) 

My model looks like this:

class AnotherAim(models.Model):

    email=models.EmailField(null=True)
    name= models.CharField(max_length=100)
    sur_name= models.CharField(max_length=100)
    code = models.OneToOneField(Aim,null=True)



class Aim(models.Model):

     code = models.CharField(max_length=5, null=False)
     ....
     ....

Upvotes: 0

Views: 104

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

I would structure my models as such:

class Aim(models.Model):
     code = models.CharField(max_length=5)

     def __unicode__(self):
         return self.code

class AnotherAim(models.Model):
    email = models.EmailField(blank=True)
    name = models.CharField(max_length=100)
    sur_name = models.CharField(max_length=100)
    aim = models.OneToOneField(Aim, null=True)

    def __unicode__(self):
        return self.name  # or another field

Upvotes: 1

Related Questions