如何在Django模型中存储函数 [英] How to store functions in django models

查看:182
本文介绍了如何在Django模型中存储函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我完全重写了这个问题,因为原始问题没有清楚地解释我的问题

edit: I completely rewrote the question as the original one didn't clearly explain my question

我想运行一个特定于每个特定模型实例的函数.

I want to run a function which is specific to each particular model instance.

理想情况下,我想要这样的东西:

Ideally I want something like this:

class MyModel(models.Model):
    data = models.CharField(max_length=100)
    perform_unique_action = models.FunctionField() #stores a function specific to this instance

x = MyModel(data='originalx', perform_unique_action=func_for_x)
x.perform_unique_action() #will do whatever is specified for instance x

y = MyModel(data='originaly', perform_unique_action=func_for_y)
y.perform_unique_action() #will do whatever is specified for instance y

但是,没有数据类型FunctionField.通常,这可以通过继承解决,并创建MyModel的子类,也许是这样的:

However there is no datatype FunctionField. Normally this would be solvable with inheritance, and creating subclasses of MyModel, maybe like this:

class MyModel(models.Model):
    data = models.CharField(max_length=100)
    perform_unique_action = default_function

class MyModelX(MyModel):
    perform_unique_action = function_X

class MyModelY(MyModel):
    perform_unique_action = function_Y

x = MyModelX(data='originalx')
x.perform_unique_action() #will do whatever is specified for instance x

y = MyModelY(data='originaly')
y.perform_unique_action() #will do whatever is specified for instance y

不幸的是,我不认为我可以使用继承,因为我试图通过这种方式访问​​该函数:

Unfortunately, I don't think I can use inheritance because I am trying to access the function this way:

class MyModel(models.Model):
    data = models.CharField(max_length=100)
    perform_unique_action = default_function

class SecondModel(models.Model):
    other_data = models.IntegerField()
    mymodel = models.ForeignKey(MyModel)

secondmodel = SecondModel.objects.get(other_data=3)
secondmodel.mymodel.perform_unique_action()

问题似乎是,如果我在子类中覆盖perform_unique_action,我不知道外键在SecondModel中将是哪种类型.

The problem seems to be that I don't know what type the foreign key is going to be in SecondModel if I override the perform_unique_action in subclasses.

我可以从SecondModel作为外键访问MyModel,并且对每个MyModel实例仍然具有唯一的功能吗?

Can I access MyModel from SecondModel as a foreign key and still have a unique function for each instance of MyModel?

推荐答案

这对我有用.我还没有测试过,但是您应该能够创建另一个类并覆盖它们的方法,这样就可以了.检查class Meta行,它将其视为抽象类.这是我现在正在练习的实际课程的示例.

This works for me. I haven't tested it, but you should be able to create another class and override their methods and it'll work. Check the class Meta line, it'll treat it as an abstract class. Here's an example of my actual classes that I'm working on right now.

编辑:添加了VoteComment类并对其进行了测试.它按预期工作!

Added VoteComment class and tested it. It works as expected!

class Vote(models.Model):
    VOTE_ENUM = (
        (VoteEnum.DOWN_VOTE, VoteEnum.toString(VoteEnum.DOWN_VOTE)),
        (VoteEnum.NONE, VoteEnum.toString(VoteEnum.NONE)),
        (VoteEnum.UP_VOTE, VoteEnum.toString(VoteEnum.UP_VOTE)),

    )
    question = models.ForeignKey(Question, null=False, editable=False, blank=False)
    voter = models.ForeignKey(User, blank=False, null=False, editable=False)
    vote_type = models.SmallIntegerField(default=0, null=False, blank=False, choices=VOTE_ENUM)

    class Meta:
        abstract = True

    def is_upvote(self):
        return self.vote_type > 0
    def is_downvote(self):
        return self.vote_type < 0

class VoteAnswer(Vote):
    answer = models.ForeignKey(Answer, null=False, editable=False, blank=False)

    class Meta:
        unique_together = (("voter", "answer"),) # to prevent user from voting on the same question/answer/comment again

    def __unicode__(self):
        vote_type = "UP" if vote_type > 0 else ("DOWN" if vote_type < 0 else "NONE")
        return u"{0}: [{1}] {2}".format(user.username, vote_type, answer.text[:32])

    def is_upvote(self):
        return "FOO! "+str(super(VoteAnswer, self).is_upvote())

class VoteComment(Vote):
    comment = models.ForeignKey(Comment, null=False, editable=False, blank=False)

    class Meta:
        unique_together = (("voter", "comment"),) # to prevent user from voting on the same question/answer/comment again

    def __unicode__(self):
        vote_type = "UP" if vote_type > 0 else ("DOWN" if vote_type < 0 else "NONE")
        return u"{0}: [{1}] {2}".format(user.username, vote_type, comment.text[:32])

    def is_upvote(self):
        return "BAR!"

这篇关于如何在Django模型中存储函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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