0

i have two model "product detail" and "status"

class product_detail(models.Model):
     modelNO=models.CharField(max_length=50)
     Channels=models.CharField(max_length=50)

class status(models.Model):
     machineinfo=models.ForeignKey(product_detail,on_delete=models.CASCADE)
     state=models.IntegerField(blank=False,default='0')

in admin page, product detail (eg:modelNO=RX100) will be added by staff, when product detail is added,.status also need to create for that object (modelNO=RX100)

now "status" is not creating with default value when "product_detail" is created in admin page,. so when i update data in status by using below code..it shows error

obj=production_detail.objects.get(modelNO="RX100")                              
stobj=status.objects.get(machineinfo=obj)

it shows error

logs.models.DoesNotExist: status matching query does not exist

how to create "status" objects automatically when "product_detail" is created in admin page

admin.py

`class status_admin(admin.ModelAdmin):
     model=status
     list_display=("machineinfo","state")

 class product_admin(admin.ModelAdmin):
      model=production_detail
      list_display=('modelNO','channels')
trantu
  • 1,089
  • 8
  • 17
masternone
  • 429
  • 5
  • 13

1 Answers1

1

You can use Signals:

from django.db.models.signals import post_save
#if a new object of product_detail is created then a new status should be created automatically
@receiver(post_save, sender=production_detail)
def create_status(sender, instance, created, *args, **kwargs):
    if created:
          obj = status(machineinfo=instance)
          obj.save()
trantu
  • 1,089
  • 8
  • 17