如何使用ForegnKey查找来更新模型中的字段?

时间:2019-10-29 19:12:32

标签: django django-models

我需要能够更新num_places模型中的字段Event,并在保存最后一个时通过event模型中的Participant ForeignKey访问它。

这是我的 models.py

class Event(models.Model):
    name = models.CharField(max_length=50)
    description = models.CharField(max_length=500)
    text = models.TextField()
    image = models.ImageField(blank=True)
    date = models.DateTimeField()      
    price = models.PositiveIntegerField()
    num_places = models.PositiveIntegerField(default=50)       
    slug = models.SlugField()

class Participant(models.Model):
    name = models.CharField(max_length=200)
    participant_uuid = models.UUIDField(primary_key=False, verbose_name='UUID')
    email = models.EmailField()
    phone_regex = RegexValidator(regex=r'^\+7\d{10}$')
    phone_number = models.CharField(validators=[phone_regex], max_length=12)
    num_places = models.PositiveIntegerField(default=1)        
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    paid = models.BooleanField(default=False)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        try:
            self.full_clean(exclude=None)
            self.event.num_places -= self.num_places # the value isn't updated
            super().save(*args, **kwargs)
            self.valid = True
            self.non_field_errors = False
        except ValidationError as e:
            self.non_field_errors = e.message_dict[NON_FIELD_ERRORS]
            self.valid = False

    class Meta:
        unique_together = ('name', 'email', 'phone_number', 'event')

带有注释的代码有问题:num_places模型中的Event值保持不变。如何解决?

1 个答案:

答案 0 :(得分:1)

您需要保存Event的修改后的对象。 self.event.save()

 def save(self, *args, **kwargs):
    try:
        self.full_clean(exclude=None)
        self.event.num_places -= self.num_places # the value isn't updated
        self.event.save()
        """watch out this since you wanna do it at the end after setting valid, and non_fieild_errors"""
        super().save(*args, **kwargs)
        self.valid = True
        self.non_field_errors = False
    except ValidationError as e:
        self.non_field_errors = e.message_dict[NON_FIELD_ERRORS]
        self.valid = False