How to make this kind of relationship in Django?

I have the models "subscriber":

class Assinante(models.Model):
    name = models.CharField("Nome", max_length=32, null=False, blank=True)
    phone = models.CharField("Telefone", max_length=11, null=True, blank=True)
    email = models.EmailField("E-mail", null=True, blank=True)
    plans = models.ForeignKey("Plano", null=True, blank=True)
    start_date = models.DateField("Data da assinatura", null=False, blank=False)
    due_date = models.DateField("Vencimento", null=False, blank=False)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Assinantes"

And the "flat" models:

class Plano(models.Model):
    name = models.CharField("Nome", max_length=32, null=False, blank=False, unique=True)
    price = models.FloatField("Valor pago", default=00.00)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Planos"

As it is possible to notice in " subscriber "I have a foreign key referencing the" plan "of the"subscriber". What I want is to have a field in "subscriber" that stores the value of the variable price set to "plan", but this value needs to be related to the table of the chosen plan in the variable plans , for example I registered a name Plan Gold with the price 79.99, when I add a subscriber and set his plan to Gold I want automatically the column value Paid Value to be 79.99. Example below.

I need this to work in a Django-Admin table, can anyone help me ?

Assinantes
| Nome   | Telefone     | E-mail            | Planos    | Valor pago |
| Carlos | 88 952684179 | [email protected] | Gold      | 79,99      |
| Mario  | 88 910101799 | [email protected] | Platinium | 119,99     |
Planos
| Plano     | Preço  |
| Prata     | 29,99  |
| Gold      | 79,99  |
| Platinium | 119,99 |
Author: adevontheroad, 2020-02-28

1 answers

From what I understand you just need to show the data in the django admin table in this way. To do this, you create a class in the admin file, with the following:

class AssinanteAdmin(admin.ModelAdmin):
    resource_class = Assinante
    list_display = ('name', 'phone', 'email', 'get_name', 'get_price')
    search_fields = ['name', 'phone']

    def get_name(self, obj):
        return obj.plans.name

    def get_price(self, obj):
        return obj.plans.price

admin.site.register(Assinante, AssinanteAdmin)

That is, create the table definitions and for your FK you create a function for each attribute you want to show in the grid.

Result.

insert the description of the image here

 1
Author: Ernesto Casanova, 2020-03-06 00:19:45