fabulias
fabulias

Reputation: 121

How to create dictionary key-values in django

I am developing server web with Django, and my model ST_Folio contains idST and idFolio, I need to create a dictionary {idST: [idFolio1, idFolio2, ...]}

But my problem is that I can create similar dictionary but no like I want.

I am using this method for this..

st_database = St_folio.objects.exclude(idST__isnull=True)
dictionary = {k: list(g) for k, g in groupby(st_database, key=lambda q: q.idST)}

and obtains this

First print (st_database):

<QuerySet [<St_folio: 1st_folio>, <St_folio: 2st_folio>, <St_folio: 3st_folio>]>

Second print (dictionary):

{<ST: st1>: [<St_folio: 1st_folio>, <St_folio: 2st_folio>], <ST: st2>: [<St_folio: 3st_folio>]}

I need thing like this:

{<ST: st1>: [<idFolio: folio1>, <idFolio: folio20>], <ST: st2>: [<idFolio: folio1>]}

My model ST_Folio

class St_folio(models.Model):
    idST = models.ForeignKey('ST', blank=True, null=True)
    idFolio = models.ForeignKey('Folio', blank=True, null=True)
    class Meta:
        unique_together = (('idST', 'idFolio'),)
    idPro = models.ForeignKey('Pro', blank=True, null=True)
    path_img = models.TextField(blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    lng = models.FloatField(blank=True, null=True)
    lat = models.FloatField(blank=True, null=True)
    date = models.DateTimeField(blank=True, null=True)
    def __str__(self):
        return str(self.id) + "st_folio"

Thanks!!

Upvotes: 1

Views: 765

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

You could access the related objects and build a list from those:

dct = {k: [x.idFolio for x in g] for k, g in groupby(st_database, key=lambda q: q.idST)}

Also, note that groupby requires that the iterable be presorted, therefore, you may want to order your QuerySet befoere applying groupby:

st_database = St_folio.objects.exclude(idST__isnull=True).order_by('idST')

Or:

st_database = St_folio.objects.exclude(idST__isnull=True).order_by('idST_id')

in case you have a different field specified for Meta.ordering.

You can also add select_related to fetch the related object and optimize access to the related objects.

Upvotes: 3

Related Questions