Home > Enterprise >  django rest_framework when creating object says get() returned more than one Request -- it returned
django rest_framework when creating object says get() returned more than one Request -- it returned

Time:12-05

I'm creating a api where everytime someone request for repairs it also saves in inspection table

when I try to post in postman

{
"reqdescription": "test",
"techofficeid": "ICT"
}

this is the row of request

|reqid|reqdescription|reqdate|officerequestor|techofficeid|
| 36  | test         |2022...|    HR         |     ICT    |

while this is the row of inspection

|inspectid|reqid| etc...|    description    |
| 5       | 36  |.......|Request object (36)|

instead of test why it's Request object (36)

this is my signals.py

@receiver(post_save, sender=Request)
def create_transaction_log(sender, instance, created, **kwargs):
if created:
  Inspection.objects.create(reqid=Request.objects.get(reqid=instance.reqid),
    description=Request.objects.get(reqdescription=instance.reqdescription),
    reqdate=str(datetime.now().strftime('%Y-%m-%d')))

my assumptions is because of OneToOneField but maybe I was wrong

Hope someone can help

models.py

class Inspection(models.Model):
inspectid = models.AutoField(primary_key=True)
reqid = models.OneToOneField('Request', models.DO_NOTHING, db_column='reqid', blank=True, null=True)
insdate = models.DateField(blank=True, null=True)
diagnosis = models.CharField(max_length=100, blank=True, null=True)
inspector = models.ForeignKey('Technician', models.DO_NOTHING, db_column='inspector', blank=True, null=True)
isinspected = models.BooleanField(default='False', blank=True, null=True)
description = models.CharField(max_length=100, blank=True, null=True)
reqdate = models.DateField(blank=True, null=True)

class Meta:
    managed = False
    db_table = 'inspection'

class Request(models.Model):
reqid = models.AutoField(primary_key=True)
reqdescription = models.CharField(max_length=100, blank=True, null=True)
reqdate = models.DateField(auto_now_add = True, blank=True, null=True)
officerequestor = models.ForeignKey('Office', models.DO_NOTHING, db_column='officerequestor', blank=True, null=True)
techofficeid = models.ForeignKey('Technicianoffice', models.DO_NOTHING, db_column='techofficeid', blank=True, null=True)

class Meta:
    managed = False
    db_table = 'request'

CodePudding user response:

In the create_transaction_log signal you already have the Request object in instance parameter. So, you don't need to do Request.objects.get... there. Instead, use instance, like this:

@receiver(post_save, sender=Request)
def create_transaction_log(sender, instance, created, **kwargs):
if created:
  Inspection.objects.create(
    reqid=instance,
    description=instance.reqdescription,
    reqdate=instance.reqdate,
  )

BTW, I would not choose Request name for the model, to avoid associations with HTTP request.

  • Related