Django管理员保存覆盖

时间:2019-02-14 23:08:58

标签: django save override admin

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

该表库存具有来自汽车表的外键。 我希望管理员每次将库存的确认字段保存为“已批准”时,汽车的确认字段也保存为“已批准”。

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

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) 

但它不起作用

1 个答案:

答案 0 :(得分:1)

您需要保存汽车对象

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)