django-创建相关forigenkey模型对象时需要创建模型对象

django-need to create model object when related forigenkey model object is created

我有两个模型 "product detail" 和 "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')

在管理页面中,工作人员将添加产品详细信息(例如:modelNO=RX100),添加产品详细信息时,还需要为该对象创建.status(modelNO=RX100)

现在 "status" 在管理页面中创建 "product_detail" 时未使用默认值创建。所以当我使用下面的代码更新状态中的数据时..它显示错误

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

显示错误

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

如何在管理页面中创建 "product_detail" 时自动创建 "status" 对象

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')

您可以使用 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()