Home > other >  django Item matching query does not exist
django Item matching query does not exist

Time:09-07

I have an app that when someone saves an item it also save on item_transactionlog but when I try to run the code it's throwing an error api.models.Item.DoesNotExist: Item matching query does not exist.

here's my models.py

class Item(models.Model):
cl_itemid = models.CharField(primary_key=True, max_length=20)
studid = models.CharField(max_length=9, blank=True, null=True)
office = models.ForeignKey('ClearingOffice', models.DO_NOTHING, blank=True, null=True)
sem = models.CharField(max_length=1, blank=True, null=True)
sy = models.CharField(max_length=9, blank=True, null=True)
remarks = models.TextField(blank=True, null=True)
resolution = models.TextField(blank=True, null=True)
resolve = models.BooleanField(blank=True, null=True)
resolve_date = models.DateField(blank=True, null=True)
resolve_by = models.CharField(max_length=8, blank=True, null=True)
recorded_by = models.CharField(max_length=8, blank=True, null=True)
record_date = models.DateField(blank=True, null=True)

class Meta:
    managed = False
    db_table = 'item'

def save(self, *args, **kwargs):
    ItemTransactionLog.objects.create(
        cl_itemid=Item.objects.get(cl_itemid=self.cl_itemid),
        trans_desc='Add Clearance Item',
        trans_recorded=timezone.now()
    )
    super(Item, self).save(*args, **kwargs)

something is wrong in the cl_itemid=Item.objects.get(cl_itemid=self.cl_itemid) I just dont know how to fix it. hope someone can help

CodePudding user response:

The problem is - you are trying to get the record that has not been saved, you can firstly save the object, and after that create the log:

def save(self, *args, **kwargs):
    super(Item, self).save(*args, **kwargs)
    ItemTransactionLog.objects.create(
        cl_itemid=Item.objects.get(cl_itemid=self.cl_itemid),
        trans_desc='Add Clearance Item',
        trans_recorded=timezone.now()
    )

And also, in stead of fetching from DB, you can simply use self.id:

ItemTransactionLog.objects.create(
    cl_itemid=self.id,
    ...
)

CodePudding user response:

You must define your ItemTransactionLog object creation in a post_save signal. The foreign object is not saved when you are calling the create method.

Suggested resolution:

Create a post_save signal

Define a function:

def create_transaction_log(sender, instance, **kwargs):
        ItemTransactionLog.objects.create(
        cl_itemid=instance,
        trans_desc='Add Clearance Item',
        trans_recorded=timezone.now()
    )

Then connect this function:

post_save.connect(create_transaction_log,sender=Item)

CodePudding user response:

You try fetch an Item that it is just about to be created, in fact into save function new Item object with new cl_itemid is being created and has not been created!

So you can't have query cl_itemid=Item.objects.get(cl_itemid=self.cl_itemid)

One solution for this is using Signals

  • Related