简体   繁体   中英

Django:How to pass a foreign key value in pre_save signal?

This are my models:

class Ledger1(models.Model):
    creation_Date   = models.DateField(default=datetime.date.today,blank=True, null=True)
    name            = models.CharField(max_length=32)
    group1_Name     = models.ForeignKey(Group1,on_delete=models.CASCADE,null=True,related_name='ledgergroups')

class Journal(models.Model):
    date            = models.DateField(default=datetime.date.today)
    voucher_id      = models.PositiveIntegerField(blank=True,null=True)
    voucher_type    = models.CharField(max_length=100,blank=True)
    by              = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Debitledgers')
    to              = models.ForeignKey(Ledger1,on_delete=models.CASCADE,related_name='Creditledgers')
    debit           = models.DecimalField(max_digits=10,decimal_places=2,null=True)
    credit          = models.DecimalField(max_digits=10,decimal_places=2,null=True)

This is my signal:

@receiver(pre_save, sender=Journal)
def pl_journal(sender,instance,*args,**kwargs):
    if instance.Debit != None or instance.Credit != None or instance.By.group1_Name.group_Name == 'Indirect Expense':
        Journal.objects.update_or_create(date=instance.date, voucher_id=instance.id, voucher_type= "Journal",by=instance.by,to=Ledger1.objects.get(name='Profit & Loss A/c'),debit=instance.debit,credit=instance.credit)

I want to pass a pre_save signal that whenever a Journal objects is created which is having a Group1 object name of Indirect Expense another journal with the same by with the to value of 'Profit & Loss A/c' should be automatically created...

This line of code is giving me a error:

Ledger1.objects.get(name='Profit & Loss A/c')

Error:

get() returned more than one Ledger1 -- it returned 2!

Can anyone tell me how to get a Foreign key object in a pre_save signal?

Thank you

The get() is to be used when you expect only one result to be returned. So, you should use some other unique input which returns the only unique result you would expect.

Alternatively, if you actually want more than 1 result to be returned, use the filter() method instead. Something like,

Ledger1.objects.filter(name='Profit & Loss A/c')

But in your case, it seems only 1 result is expected, so I recommend using a unique input or a workaround would be :-

Ledger1.objects.filter(name='Profit & Loss A/c').first()

This would return a single result which is only the first fetched result, if that's okay with the kind of logic you are trying to implement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM