Michael
Michael

Reputation: 43

django Item matching query does not exist

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

Upvotes: 1

Views: 72

Answers (2)

Ersain
Ersain

Reputation: 1520

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,
    ...
)

Upvotes: 1

Rohit Rahman
Rohit Rahman

Reputation: 1153

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)

Upvotes: 1

Related Questions