How to generate auto increment field, in Django models, that is not PK, and that depends on information from another field that is FK?

Asked

Viewed 62 times

0

I’m developing an application in Django that has two models, Modality and Bidding. The Bidding has a FK field (models.Foreingkey), which pulls the Modality. I would like this field to generate an automatic, increasing value (001,002,003) for each Modality.

In this way, to: the mode XXX I can have bidding 001,002,003 .... 999 The YYY mode I can have tender 001,002,003 .... 999

And so on, but in every mode this numbering does not repeat itself.

The code is more or less this:

class Modalidade(models.Model):
    modalidade = models.CharField(max_length=20)


class Licitacao(models.Model):
    modalidade = models.ForeignKey(Modalidade, on_delete=models.CASCADE)
    licitacao = models.CharField(max_length=5)
    objeto = models.CharField(max_length=50)
    ...

2 answers

1

I decided as follows, taking advantage of the help of friend Pablo:

class Licitacao(models.Model): modality = models.Foreignkey(Modality, on_delete=models.CASCADE) licitation = models.Positivesmallintegerfield()

def save(self, *args, **kwargs):
    self.licitacao = Licitacao.objects.filter(modalidade=self.modalidade).count() + 1
        return super().save(*args, **kwargs)  # Continue with save as normal
   

0

The field with this numbering cannot be PK or FK because it repeats. But if you want to use an auxiliary field to store this numbering ok. Assuming the field is called "numbering", the simplest and most obvious way to do this is to create the object, calculate the field and save. See the example:

uma_modalidade = Modalidade.objects.get(id=123)
nova_licitacao = Licitacao(modalidade=uma_modalidade)
nova_licitacao.numeracao = Licitacao.objects.filter(modalidade=uma_modalidade).count() + 1
nova_licitacao.save()

Another alternative is to override the save method, but there are some things that are outside the scope of this question.

  • This code is implemented in function form in Models, or in Forms?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.