更改外键对象的字段

我有以下问题。

我有一个模型Towar

class Towar(models.Model):
  nrSeryjny = models.CharField(max_length=100)
  opis = models.CharField(max_length=255)
  naStanie = models.NullBooleanField(null=True)

  def __unicode__(self):
      return "%s" % self.opis

  def lowerName(self):
      return self.__class__.__name__.lower()

  def checkState(self):
      return self.naStanie

  def changeState(self,state):
      self.naStanie=state

  class Meta:
      ordering=['nrSeryjny']
      app_label = 'baza'
      permissions=(("view_towar","mozna miec podglad dla towar"),)

另一种模式是Wypozyczenie ,它通过外键关系与Towar连接:

class Wypozyczenie(models.Model):
    dataPobrania = models.DateField()
    pracownik = models.ForeignKey(User,null=True)
    kontrahent = models.ForeignKey(Kontrahenci,null=True)
    towar = models.ForeignKey(Towar,null=True)
    objects = WypozyczenieManager()
    default_objects = models.Manager()

    ZwrotyObjects = WypozyczenieZwrotyManager()

    def lowerName(self):
        return self.__class__.__name__.lower()

    def __unicode__(self):
        if self.towar == None:
            return "Dla:%s -- Kto:%s -- Kiedy:%s -- Co:%s" % (self.kontrahent,self.pracownik,self.dataPobrania,"Brak")
        else:
            return "Dla:%s -- Kto:%s -- Kiedy:%s -- Co:%s" % (self.kontrahent,self.pracownik,self.dataPobrania,self.towar)

    class Meta:
        ordering = ['dataPobrania']
        app_label = 'baza'
        permissions = (("view_wypozyczenie","mozna miec podglad dla wypozyczenie"),)

并添加模型的视图:

def modelAdd(request,model,modelForm):
    mod = model()
    if request.user.has_perm('baza.add_%s' % mod.lowerName()):
        if request.method == 'POST':
            form=modelForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('/'+ mod.lowerName() + '/')
        else:
            form = modelForm()
            v = RequestContext(request,{'form':form})
            return render_to_response('add_form.html',v)

我想要的是,当我添加Wypozyczenie并保存它时, Towar存储的Wypozyczenie将其naStanie字段从True更改为False。

电贺


如果你想永远保持这两个同步,你可以覆盖Wypozyczenie的save()方法。

class Wypozyczenie(models.Model):
    ...

    def save(self):
        self.towar.naStanie = False
        self.towar.save()

或者,您也可以重写ModelForm的save()方法。


你有什么尝试?

你不能放?

myinstance = form.save()
towar = myinstance.towar
towar.naStanie = False
toware.save()

而不是您在视图中简单调用form.save()


您可以使用保存Wypozyczenie对象时发出的信号。 与重写save() ,它可能有点“更干净”,特别是在重用其他模型的函数时有用:

@receiver(models.signals.post_save, sender=Wypozyczenie)
def after_wypozyczenie_save(sender, instance, created, **kwargs):
    # `instance` is your saved Wypozyczenie object, you can
    # access all it's fields here:
    instance.towar.naStanie = False
    instance.towar.save()

    # It's also possible to do different action on the first save
    # and on subsequent updates:
    #
    # if created:
    #     ...
    # else:
    #     ...

还有其他信号在保存或删除之前发送。 关于信号的Django文档在这里非常有用。

链接地址: http://www.djcxy.com/p/56509.html

上一篇: Change Field of Foreign Key Object

下一篇: Django ModelForm foreign key filtering