Hello
I’m learning Django for motnh now with a smal app I build.
Now I try to display some linked fields from a model to another one in my admin page.
I don’t understand if it’s possible and how
My models are ModelB and ModelA like this :
class ModelB(models.Model):
name = models.CharField(max_length=50)
prix=models.CharField(max_length=50)
long=models.IntegerField()
larg=models.IntegerField()
def __str__(self):
return self.full_name
class ModelA(models.Model):
code = models.CharField(max_length=50, unique=True, help_text="Code")
foreignkey = models.ForeignKey(ModelB,on_delete=models.CASCADE)
My admin.py
@admin.register(ModelB)
class ModelB(admin.ModelAdmin):
list_display = ('name','prix','long','larg')
# yes it works
class ModelAAdmin(admin.ModelAdmin):
list_display = ('code', 'foreignkey',)
#list_display = ('code', 'foreignkey','my prix from Model B', 'my long from ModelB'....)
admin.site.register(ModelA, ModelAAdmin)
So now I want to display in the ModelA admin page : for each item in my ModelA database ,all fields taken from ModelB (prix,long,larg)
How do I do ?
Thank for your explanations
Patrice
You should be able to access the foreign fields using the “dot notation” just like you would reference those fields anywhere else:
list_display=(‘code’, ‘foreignkey.prix’, ‘foreignkey.long’, ‘foreignkey.larg’)
Hello Ken thanks for your reply , I try your solutions but the django server show an error
<class 'blog.admin.ModelAAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'foreignkey.prix', which is not a callable, an attribute of 'ModelAAdmin', or an attribute or method on 'blog.ModelA'.
Well, that’s what I get for relying upon my memory. The list_display docs do show that you can do this by creating functions in your admin class to return these values.
You could add functions like this in ModelAAdmin (one function for each value):
def fk_prix(self, obj):
return obj.foreignkey.prix
and then list_display = ('code', 'fk_prix', ...)
1 Like
Also, if this is something that you would want to do in multiple locations, you could also create functions like this in the Model class as well. (Again, see the docs for examples.)
Yes it work’s !! and today I understand something more in the Django’s logic
I had read the page you mention (many times) but not understood how I can use it in my propre models but now yes
Thanks for your help and explanations