Django - Standalone - How to validate value received from a Foreign key field?

Asked

Viewed 18 times

0

I am working on a Django project whose purpose is to take advantage of models for both forms and frontend views and for a separate service. For this I found a way to transform/use Django models with all their ORM in standalone mode, that is, without the need to have a Django server running.

I have the following model "Agenteda":

from django.db import models
from user.admin import User
        
class AgenteDa (models.Model):
    id_agentes_da = models.AutoField(auto_created=True, primary_key=True,  serialize=False, verbose_name='Código')
    ativo = models.BooleanField(verbose_name='ATIVO')
    data_cadastro = models.DateTimeField(auto_now_add=True, editable=False, verbose_name='Data cadastro')
    data_alteracao = models.DateTimeField(auto_now=True, editable=False, verbose_name='Data alteração')
    servidor = models.CharField(max_length=50, verbose_name='Servidor')
    total = models.IntegerField(verbose_name='Total')
    atual = models.IntegerField(verbose_name='Atual')
    diferenca = models.IntegerField(verbose_name='Diferença')
    usuario = models.ForeignKey(User, verbose_name='Usuario',on_delete=models.CASCADE)
    

    class Meta:
        db_table = 'agente_da'
        verbose_name_plural = 'agentes_da'

    def __unicode__(self):
        return f"{self.id_agentes_da} - {self.servidor} - {self.total} - {self.atual} - {self.diferenca} - {self.ativo} - {self.usuario}"
        
    def save(self, *args, **kwargs):
        self.usuario = self.usuario if len(User.objects.filter(username=self.usuario)[0]) != 0 else User.objects.filter(username='robo')[0] 
        super().save(*args, **kwargs)

The "self.usuario" field is a Foreign key of the "user" model".

In my script where I call the model "Agenteda", I pass the information:

agente_da = AgenteDa()
agente_da.ativo = True
agente_da.servidor = "Cleber"
agente_da.atual = 37
agente_da.total = 47
agente_da.diferenca = 23
# agente_da.usuario = User.objects.filter(username='robo')[0]
agente_da.save()

In this case I am omitting the "agente_da.usuario" field on purpose to fall into the validation within the "Agenteda" model. This is where I’m in trouble.

When doing this, that is, do not pass information in the "agente_da.usuario" field, when it arrives in the function save() model generates error:

raise self.Relatedobjectdoesnotexist( db.models.agente_da_models.Relatedobjectdoesnotexist: Agenteda has no usuario

My question is: How do I validate "self user." within the model whether or not it is receiving information?

When I just do it like this:

if not self.usuario:
    self.usuario = User.objects.filter(username='robo')[0]

I get error like this: Valueerror: Cannot assign "<Queryset [<User: robo>]>": "Agenteda.usuario" must be a "User" instance. or so: db.models.agente_da_models.Relatedobjectdoesnotexist: Agenteda has no usuario.

1 answer

0

I’ll put on record how I managed to resolve, in case anyone has this problem, or has a better solution.

Finally I managed to solve it by doing this way: Since I couldn’t find a better way to read, or validate 'self user.', I discovered an exception to faqzer this treatment:

try:
            self.usuario = self.usuario
        except (User.MultipleObjectsReturned, User.DoesNotExist):
            self.usuario = User.objects.filter(username="robo")[0]

Thus even without information on 'self user.' I can handle the Exception generated.

Such a solution was possible with this reference: https://stackoverflow.com/questions/7877340/typeerror-doesnotexist-object-is-not-callable

If anyone has a better solution, they’re welcome.

Browser other questions tagged

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