Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add field from another model Django

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.

like image 426
antonio Avatar asked Jul 31 '12 16:07

antonio


3 Answers

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.)

like image 55
Daniel Roseman Avatar answered Sep 22 '22 20:09

Daniel Roseman


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.

like image 26
Tisho Avatar answered Sep 22 '22 20:09

Tisho


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

like image 23
antonio Avatar answered Sep 20 '22 20:09

antonio