Django—模型中的函数。如何从视图中调用它?

时间:2023-01-24 11:23:53

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.

我正在Django设计一个模型,但我不知道这是否是最好的方法。我有一个名为“History”的模型,在这个模型中我有一个专门的函数来处理这个模型的插入。

Alternative 1

选择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

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

要将数据插入到历史模型中,我将不得不使用“insert_history”函数。

My questions here are:

我的问题是:

The code above is correct?

以上代码是否正确?

If yes, how can I call the "insert_history" from a view?

如果是,如何从视图中调用“insert_history”?


Alternative 2

选择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')

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

正确的做法是什么?如果选项1是正确的,我如何从视图中调用“insert_history”?

Best Regards,

最好的问候,

4 个解决方案

#1


10  

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

insert_history使用自我吗?还是创建一个新的历史对象?

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

To call it

叫它

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

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

顺便说一句,创建新对象的方法的常规名称是create。同样,请查看https://docs.djangoproject.com/en/1.9/ref/models/instances/#creating-objects

#2


2  

Just select your History instance (eg. with primary key 1):

只需选择历史实例(如。1)主键:

hist = History.objects.get(pk=1)

...and call your method using the hist variable:

…使用hist变量调用方法:

hist.insert_history(...)

#3


1  

I think that it is most appropriate to use custom manager https://docs.djangoproject.com/en/dev/topics/db/managers/ for this problems.

我认为最适合使用自定义管理器https://docs.djangoproject.com/en/dev/topics/db/managers/来解决这个问题。

#4


0  

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

要向历史模型插入数据,我必须始终使用insert_history函数。

Yes, it will set the field3, a datetime, based on some logic that I will write inside insert_history

是的,它将设置field3,一个datetime,基于我将在insert_history中编写的一些逻辑

The easiest way is to override the save method:

最简单的方法是重写保存方法:

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

    def __unicode__(self):
        return unicode(self.field1.id) # __unicode__ should return unicode,
                                       # not string.

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

    def save(self, *args, **kwargs):
        self.field3 = your calculated value
        super(History, self).save(*args, **kwargs)

Now, whenever you save your method - field3's value will be whatever is the result of the calculation in your custom save method. You don't need to modify anything in your views for this to work.

现在,无论何时保存方法——field3的值将是自定义保存方法中计算的结果。您不需要修改视图中的任何内容来使其工作。

#1


10  

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

insert_history使用自我吗?还是创建一个新的历史对象?

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

To call it

叫它

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

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

顺便说一句,创建新对象的方法的常规名称是create。同样,请查看https://docs.djangoproject.com/en/1.9/ref/models/instances/#creating-objects

#2


2  

Just select your History instance (eg. with primary key 1):

只需选择历史实例(如。1)主键:

hist = History.objects.get(pk=1)

...and call your method using the hist variable:

…使用hist变量调用方法:

hist.insert_history(...)

#3


1  

I think that it is most appropriate to use custom manager https://docs.djangoproject.com/en/dev/topics/db/managers/ for this problems.

我认为最适合使用自定义管理器https://docs.djangoproject.com/en/dev/topics/db/managers/来解决这个问题。

#4


0  

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

要向历史模型插入数据,我必须始终使用insert_history函数。

Yes, it will set the field3, a datetime, based on some logic that I will write inside insert_history

是的,它将设置field3,一个datetime,基于我将在insert_history中编写的一些逻辑

The easiest way is to override the save method:

最简单的方法是重写保存方法:

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

    def __unicode__(self):
        return unicode(self.field1.id) # __unicode__ should return unicode,
                                       # not string.

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

    def save(self, *args, **kwargs):
        self.field3 = your calculated value
        super(History, self).save(*args, **kwargs)

Now, whenever you save your method - field3's value will be whatever is the result of the calculation in your custom save method. You don't need to modify anything in your views for this to work.

现在,无论何时保存方法——field3的值将是自定义保存方法中计算的结果。您不需要修改视图中的任何内容来使其工作。