Francisco Ghelfi
Francisco Ghelfi

Reputation: 962

Django printing dynamic field in template

With a given model:

class Ventas(models.Model):
    producto = models.CharField(max_length=200, help_text="", blank=True, null=True)
    stock = models.IntegerField(help_text="Tier", blank=True, null=True)
    marca = models.ForeignKey(Marcas, help_text="Usuario", blank=True, null=True, on_delete=models.CASCADE)
    categoria = models.ImageField(upload_to='', default="", blank=True, null=True)

    def __str__(self):
        return str(self.producto )

I annotate a queryset using a dynamicaly chosen field as follows:

ventas_producto = ventas.values(ver_por_choices).annotate(
        uds_totales=F("uds_totales"),
        share=F("uds_totales"),
        ).order_by('-uds_totales')

The var "ver_por_choices" can take values of the fields of the model: producto, stock, marca or categoria

Then in the template I want to print the values as

{% for venta in ventas_producto %}
    <div>{{ venta.uds_totales}}</div>
    <div>{{ venta.share}}</div>
{% endfor %}

How can I print the dynamic field?

Upvotes: 1

Views: 55

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

Why not include it in the queryset as key:

ver_por_choices = 'Some field name'

ventas_producto = ventas.values(ver_por_choices).annotate(
    uds_totales=F('uds_totales'),
    share=F('uds_totales'),
    key=F(ver_por_choices)
).order_by('-uds_totales')

or even more convenient:

ventas_producto = ventas.values(
    uds_totales=F('uds_totales'),
    share=F('uds_totales'),
    key=F(ver_por_choices)
).order_by('-uds_totales')

Then you can usse this in the {% for … %} loop with:

{% for venta in ventas_producto %}
    <div>{{ venta.key }}</div>
    <div>{{ venta.uds_totales}}</div>
    <div>{{ venta.share}}</div>
{% endfor %}

Upvotes: 1

Related Questions