Django - 保存在一个模型中,在另一个模型中访问

时间:2015-07-17 18:45:51

标签: django

我正在开发一款应用,可让用户创建活动并注册彩票以参加活动。因此,我需要创建模型方法,随机化那些已经进入彩票的人,并跟踪每个用户赢得的彩票数量。

我试图在1个模型(事件)中定义随机模型方法,但模型方法涉及对另一个模型属性(UserProfile)进行更改。如果我在事件上运行randomize()方法,则userprofile.events_attended属性不会更新。

我已经搜索过,很遗憾没有能够在Stack Overflow上找到任何合适的答案。任何有关如何最好地完成此任务的帮助非常感谢。

models.py

class Event(models.Model):
    name = models.CharField(max_length=30)
    hosts = models.CharField(max_length=100, blank=True)
    description = models.TextField(max_length=400)
    guests = models.PositiveIntegerField()
    date = models.DateField()
    time = models.TimeField()
    duration = models.DurationField()
    address = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        from django.core.urlresolvers import reverse
        return reverse('event_detail', args=[self.id])

    def randomize(self):
        guests = self.guests
        random = self.attendees.order_by('?')[:guests]
        for i in random:
            i.events_attended = i.events_attended + 1
            i.save()

    class Meta:
        ordering = ['-created_at']


class UserProfile(models.Model):


    user = models.OneToOneField(User)

    first_name = models.CharField(max_length=30, null=True)
    last_name = models.CharField(max_length=30, null=True)
    year = models.CharField(blank=True, max_length=5, choices=YEAR_CHOICES)
    events = models.ManyToManyField(Event, blank=True, related_name="attendees")
    events_created = models.PositiveIntegerField(blank=True, default=0)
    events_attended = models.PositiveIntegerField(blank=True, default=0)
    lottery_points = models.PositiveIntegerField(blank=True, default=0)

    def __str__(self):
        return self.user.username

    def net_lottery_points(self):
        events_attended = self.events_attended
        lottery_points = self.lottery_points
        events_created = Event.objects.filter(created_by=self.user).count()
        if events_created - events_attended <= 0:
           lottery_points = 0
        else:
            lottery_points = events_created - events_attended
        return lottery_points

0 个答案:

没有答案