django 管理员保存覆盖

django admin save override

models.py :

class Cars(models.Model):
   checking= ((_('pending'),_('pending')),
           (_('reject'),_('reject')),
           (_('approved'),_('approved')),
           (_('expired'),_('expired')),                )
   carname=models.CharField(max_length=128,verbose_name=_('carname'),unique="True")
   confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending'))
   def __str__(self):
      return str(self.carname)
   class Meta:
      verbose_name=_('car')
      verbose_name_plural=_('cars')
      ordering = ('carname',) 


class Stocks(models.Model):
   user=models.ForeignKey(User, null=True,related_name='stockdetails')
   mark=models.CharField(max_length=128,blank=True, null=True,verbose_name=_('mark'))
   pic=models.ImageField(blank=True,null=True,verbose_name=_('pic'),upload_to = 'stocks', default = 'stocks/nopic.jpg')
   car=models.ForeignKey(Cars,blank=True,null=True,verbose_name=_('car'),on_delete=models.SET_NULL ,to_field='carname')      description=models.CharField(blank=True,null=True,max_length=264,verbose_name=_('description'))
   price=models.PositiveIntegerField(blank=True,null=True,verbose_name=_('price'))
   date=models.DateTimeField(auto_now_add = True,verbose_name=_('date'))
   checking= ((_('pending'),_('pending')),
       (_('reject'),_('reject')),
       (_('approved'),_('approved')),
       (_('expired'),_('expired')),
            )
    confirm=models.CharField(choices=checking,max_length=12,verbose_name=_('confirmation'), default=_('pending'))
   def __str__(self):
       return str(self.id)

   class Meta:
       verbose_name=_('Stock')
       verbose_name_plural=_('Stocks')
   def get_absolute_url(self):
         return reverse('BallbearingSite:detailadvertisement' ,kwargs={'id':self.id})

table 库存有来自汽车 table 的外键。 我希望当管理员将库存的确认字段保存为 "approved" 时,汽车的确认字段也保存为“已批准”。

我所做的是覆盖 admin.py 中的保存方法:

class StocksAdmin(admin.ModelAdmin):
    list_display=["user","raste","stname","mark","description","pic","price","confirm","car","carbrand","date","parts_cars"]
    list_editable=["confirm",]

    def save_model(self, request, obj, form, change):
        if obj.confirm == _('approved') :
            obj.car.confirm =_('approved')
        super().save_model(request, obj, form, change)
        class Meta:
            model= Stocks
admin.site.register(Stocks,StocksAdmin) 

但是没用

您需要保存汽车对象

def save_model(self, request, obj, form, change):
    if obj.confirm == _('approved') :
        obj.car.confirm =_('approved')
        obj.car.save()
        super().save_model(request, obj, form, change)