Django-模型内的函数。如何从视图中调用它? [英] Django - Function inside a model. How to call it from a view?

查看:273
本文介绍了Django-模型内的函数。如何从视图中调用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django中设计模型,但我不知道这是否是最好的方法。我有一个名为历史记录的模型,并且在此模型中,我有一个专门的函数来处理该模型的插入。

I'm designing a model in Django but I don't know if this is the best way. I have a model called "History" and inside this model I've a specialized function that will handle the inserts to this model.

替代1

class History(models.Model):
    field1 = models.ForeignKey(Request)
    field2 = models.BooleanField()
    field3 = models.DateTimeField()

    def __unicode__(self):
        return str(self.field1.id)

    class Meta: #
        ordering = ['-field3']

    def insert_history(self):
        # Here I will have some business logic to insert the data to the history model

要将数据插入历史记录模型,我将始终必须使用 insert_history功能。

To insert data to the History model I will allways have to use the "insert_history" function.

我的问题是:

上面的代码正确吗?

如果是,如何从视图中调用插入历史记录?

替代2

我已经测试了另一个替代方法,但是可以感觉不正确。代码如下所示:

I've another alternative that I've tested and it works, but does not feel the right way. The code looks like this:

class History(models.Model):
    field1 = models.ForeignKey(Request)
    field2 = models.BooleanField()
    field3 = models.DateTimeField()

    def __unicode__(self):
        return str(self.field1.id)

    class Meta: #
        ordering = ['-field3']

def insert_history(field1, field2, field3):
    # Here I will have some business logic to insert the data to the history model

我从这样的视图中调用它:

And I call it from a view like this:

from app.models import insert_history

insert_history('1', True, 'some_date')

这样做的正确方法是什么?如果替代方法1正确,我该如何从视图中调用 insert_history?

what is the correct way of doing it? If the alternative 1 is correct, how can I call the "insert_history" from a view?

最好的问候

推荐答案

insert_history是否使用self?还是创建一个新的历史记录对象?

Does insert_history use self? Or does it create a new History object?

如果它创建了一个新对象,我会这样做:

If it creates a new object, I'd do it like this:

class History(models.Model):
    @classmethod
    def insert_history(cls, field1, field2, field3):
        # Here be code

调用它

from app.models import History
History.insert_history(field1, field2, field3)

BTW,创建新对象的方法的常规名称是 create 。另外,请查看 https://docs.djangoproject。 com / en / 1.9 / ref / models / instances /#creating-objects

BTW, the conventional name for a method creating new objects is create. Also, have a look at https://docs.djangoproject.com/en/1.9/ref/models/instances/#creating-objects

这篇关于Django-模型内的函数。如何从视图中调用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆