开发者

Change Field of Foreign Key Object

开发者 https://www.devze.com 2022-12-24 04:29 出处:网络
I have the following problem. I have a model Towar: class Towar(models.Model): nrSeryjny = models.CharField(max_length=100)

I have the following problem.

I have a model 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"),)

and another model, Wypozyczenie, which is linked to Towar by a foreign key relationship:

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 -- Ki开发者_JS百科edy:%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"),)

and a view to add models:

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)

What I want is that when I add Wypozyczenie and save it, then the Towar that is stored by Wypozyczenie changes its naStanie field from True to False.

Greets


If you want to always keep those two in sync you can override Wypozyczenie's save() method.

class Wypozyczenie(models.Model):
    ...

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

Alternatively, you can also override ModelForm's save() method.


What have you tried?

Can't you just put

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

instead of your simple call to form.save() in your view.


You can use signals emitted when saving your Wypozyczenie object. It might be a little "cleaner" than overriding save(), especially when it's useful to re-use the function for other models:

@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:
    #     ...

There are other signals sent before saving or on deletion. Django documentation on signals is quite helpful here.

0

精彩评论

暂无评论...
验证码 换一张
取 消