我想在保存模型期间更改ManyToMany字段的计数。为此,我修改了save()。 如果我运行save(),count将不会更新。 如果我第二次运行保存而不更新该字段,它将更新计数。
class UserProfile(models.Model):
follower = models.ManyToManyField('self', related_name='Followers',
blank=True, symmetrical=False)
following = models.ManyToManyField('self', related_name='Followings',
blank=True, symmetrical=False)
follower_count = models.PositiveIntegerField(null=True, blank=True,
editable=False)
following_count = models.PositiveIntegerField(null=True, blank=True,
editable=False)
class Meta:
verbose_name = 'User Profile'
verbose_name_plural = 'User Profiles'
def __str__(self):
return self.follower_count
def save(self, *args, **kwargs):
super(UserProfile, self).save(*args, **kwargs)
self.following_count = self.following.all().count()
self.follower_count = self.follower.all().count()
super(UserProfile, self).save(*args, **kwargs)
我想用save()更新计数。
答案 0 :(得分:1)
FROM wurstmeister/kafka
ADD prom-jmx-agent-config.yml /usr/app/prom-jmx-agent-config.yml
ADD jmx_prometheus_javaagent-0.10.jar /usr/app/jmx_prometheus_javaagent.jar
COPY wait-for-it.sh /wait-for-it.sh
RUN chmod +x /wait-for-it.sh
CMD ["/wait-for-it.sh", "zookeeper:2181", "--", "start-kafka.sh"]
首先获取计数,然后调用保存方法
答案 1 :(得分:1)
您可以省略第一次保存,例如:
def save(self, *args, **kwargs):
self.following_count = self.following.count()
self.follower_count = self.follower.count()
super(UserProfile, self).save(*args, **kwargs)
话虽如此,但由于以下几个原因,我不能完全确定上面的方法是一个好主意:
答案 2 :(得分:0)
如果性能不是问题,则可以将两个字段都转换为计算每次访问值的属性
class UserProfile(models.Model):
follower = models.ManyToManyField('self', related_name='Followers',
blank=True, symmetrical=False)
following = models.ManyToManyField('self', related_name='Followings',
blank=True, symmetrical=False)
@cached_property
def follower_count(self):
return self.follower.count()
@cached_property
def following_count(self):
return self.following.count()