I have the follow Models (an example, not really one):
class ModelB(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class ModelA(models.Model):
code = models.CharField(max_length=50, unique=True, help_text="Code unique")
foreignkey = models.ForeignKey(ModelB, unique=True)
And in my admin.py I have:
class ModelBAdmin(admin.ModelAdmin):
list_display = ('name',)
class ModelAAdmin(admin.ModelAdmin):
list_display = ('code', 'foreignkey')
admin.site.register(ModelA, ModelAAdmin)
admin.site.register(ModelB, ModelBAdmin)
I would make something similar to:
class ModelBAdmin(admin.ModelAdmin):
list_display = ('name', 'code')
The code must be the code-relation from ModelA-code. How I can make this?
P.D.: Sorry for my english...
Thx a lot, Antonio.
Your comments show that actually what you're interested in isn't the list display at all, but the editing. For that you should use inline forms:
class ModelAInline(admin.StackedInline):
model = ModelA
class ModelBAdmin(admin.ModelAdmin):
list_display = ('name',)
inlines = [ModelAInline]
admin.site.register(ModelA, ModelAAdmin)
Now, on the edit form, each ModelA has a list of ModelBs underneath which you can edit directly there.
(Note that instead of using a ForeignKey with unique=True, you should probably use a OneToOneField.)
You can define a custom item in list_display
this way:
class ModelBAdmin(admin.ModelAdmin):
def modelA_Codes(self, inst):
return ','.join([b.code for b in inst.modela_set.all()])
list_display = ('name', 'modelA_Codes')
Since one modelB can be attached to multiple modelA items, you probably need to return a list of the applicable codes for the specified ModelB.
Thanks to @vartec , @DanielRoseman and @Tisho . Finally, with your suggesions I have made the next (I think no it's very efficient... But the other methods raise errors...)
class SubvencionCAAdmin(admin.ModelAdmin):
search_fields = ['nombre', 'tipo', 'resumen']
def Subvencion_Code(self):
lista_subvenciones = Subvencion.objects.all()
for subvencion in lista_subvenciones :
if (self.nombre == subvencion.CA.nombre):
return subvencion.codigo
list_display = ('nombre', Subvencion_Code)
The SubvencionCAAdmin is the equivalent to "ModelB" and "Subvencion" the "ModelA".
Thanks a lot
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With