English 中文(简体)
搭配和得到 模型的信号?
原标题:django and get_model for a signal?

我有信号...

@receiver(post_save, sender=User)
def create_initial_story(sender,instance, signal, created, **kwargs):
    if created:
        Story(user = instance, title =  Random Stories ,
            description="Random stories",
            is_closed = False, is_random = True).save()

但我真的不想把这个信号放进我的模型里。

是的,我知道阻止信号运行两次的魔术, 但我不相信。为什么我的应用程序要做两倍的工作!疯狂!

有人建议我使用 django.db. models.get_model , 但我不知道如何做到这一点!

from django.db.models import get_model

@receiver(post_save, sendermodel( myapp , User ))
def create_initial_story(sender,instance, signal, created, **kwargs):
    if created:
        get_model( myapp , Story ).(user = instance, title =  Random Stories ,
            description="Random stories",
            is_closed = False, is_random = True).save()

由此产生一个例外-

无法指定“ & lt; 故事: 随机故事 & gt; ” : “ story. user” 必须是一个“ 用户” 实例 。

那么,我能做些什么来解决这个问题呢?

最佳回答

你的问题就在这里:

get_model( myapp , Story ).(user = instance, title =  Random Stories ,
        description="Random stories",
        is_closed = False, is_random = True).save()

get_model 返回模型类, 所以您仍然需要 objects. create 来实际创建实例。 而且, 您不需要结尾处的 save () 。 尝试 :

get_model( myapp , Story ).objects.create(user = instance, title =  Random Stories ,
        description="Random stories",
        is_closed = False, is_random = True)
问题回答

暂无回答




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签