如何从Django的其他函数中获取对象

时间:2019-07-05 11:54:08

标签: django python-3.x django-models django-rest-framework django-views

我有两个函数projectTimerStart来启动计时器和projectTimerStop 我想使用在projectTimerStart中创建的对象,并且想结束projectTimerStop的时间,并且应该将其保存在数据库中

ps:这两个函数都不在类中,它们都是普通函数

def projectTimerStart(request, slug):
    project_detail = Project.objects.get(slug=slug)
    b = ProjectTimer(time_started=datetime.now(),
    working_project=project_detail,
    working_freelancer=request.user
    )
    b.save()
    return HttpResponseRedirect(reverse('project_timer', kwargs= 
           {"slug":slug}))


def projectTimerStop(request,  slug):
    project_detail = Project.objects.get(slug=slug)
    #i want something here super method or something
    return HttpResponseRedirect(reverse('project_timer', kwargs=
           {"slug": slug}))

models.py

class Project(models.Model):

    project_title = models.CharField(max_length=100)
    project_description = models.TextField()
    created_by = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name='created')
    assigned_to = models.ManyToManyField(
        User, blank=True, related_name='assigned_by')
    slug = models.SlugField()
    hourly_budget = models.PositiveIntegerField(blank=True, null=True)
    technologies = models.ManyToManyField(
    Technologies, related_name='technologies_used')
    time_posted = models.DateTimeField(auto_now_add=True)
    request_id = models.ManyToManyField(
        User, related_name='requested_by', blank=True)

    def __str__(self):
        return self.project_title

    def save(self, *args, **kwargs):
        self.slug = slugify(self.project_title)
        super(Project, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('project_detail', kwargs={'slug': self.slug})

    def get_timer_url(self):
        return reverse('project_timer', kwargs={'slug': self.slug})


    def round_datetime(dt):
        minutes = round((dt.minute + float(dt.second) / 60) / 15) * 15 - 
        dt.minute
        return dt + datetime.timedelta(minutes=minutes, seconds=-dt.second)


class ProjectTimer(models.Model):
    time_started = models.DateTimeField()
    time_ended = models.DateTimeField(blank=True, null=True)
    working_project = models.ForeignKey(Project, on_delete=models.CASCADE)
    working_freelancer = models.ForeignKey(
        User, on_delete=models.CASCADE, blank=True, null=True)

1 个答案:

答案 0 :(得分:1)

如果每个项目对象都只有一个项目计时器对象,则可以将project_timer = models.OneToOneField(ProjectTimer)添加到Project模型中,并使用project_detail.project_timer访问项目计时器。

否则,您需要至少知道该project_timer的一项功能,才能从数据库中获取它。或者,您可以迭代属于该ProjectTimer的所有Project对象,并通过以下方法选择合适的对象:

models.py

class Project(models.Model):
    # Some fields
    project_timers = models.ManyToManyField(ProjectTimer)

views.py

def projectTimerStop(request,  slug):
    project_detail = Project.objects.get(slug=slug)
    for pt in project_detail.project_timers.all():
        if pt.some_field == "THIS IS CORRECT TIMER":
            # Here is your project_detail
            print(str(pt))
    return HttpResponseRedirect(reverse('project_timer', kwargs=
           {"slug": slug}))