Reputation: 16184
i have 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()
which is cool and all, but i really don't want to have this signal in my models.py
it gets "double imported" somehow, and i would rather that not happen. Yes, i know about the magic trick to stop a signal being run twice, but i just don't trust that. Why have my app do twice the work! Crazy!
Somebody suggested i use django.db.models.get_model
, but i do not know how to do this! My attempt did not quite work - here is what i tried:
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()
this yields an exception -
Cannot assign "< Story: Random Stories >": "Story.user" must be a "User" instance.
So! What can i do to fix this?
Upvotes: 1
Views: 345
Reputation: 239290
You problem is here:
get_model('myapp','Story').(user = instance, title = 'Random Stories',
description="Random stories",
is_closed = False, is_random = True).save()
get_model
returns the model class, so you still need objects.create
to actually create an instance. And, you don't need the save()
at the end. Try:
get_model('myapp','Story').objects.create(user = instance, title = 'Random Stories',
description="Random stories",
is_closed = False, is_random = True)
Upvotes: 3