2011-01-27 4 views
5

개체 생성시 Django 신호 (예 : post_save 또는 post_init)를 선택적으로 억제하거나 특정 매개 변수를 보낼 수 있는지 궁금합니다.Django에서 post_save (또는 other) 신호를 선택적으로 억제 할 수 있습니까?

내가 갖고있는 것은 User 개체로 내 코드에서 다양한 방식으로 생성 될 수 있습니다. 따라서 각각 맞춤형 개체를 각 User에 자동으로 할당하려면 post_save 신호를 사용합니다. 그러나 특정 경우에는 생성 된 Profile 개체에 바인딩하려는 추가 정보가 있습니다. 인수를 인수로 post_save 신호로 전달하는 것은 좋지만 가능하지는 않습니다.

다른 옵션은 수동으로 Profile 개체를 만드는 것입니다,하지만 나는 그 User 저장 한 후, 그렇지 않으면 ProfileUser 인스턴스에 바인딩 할 수 없습니다 필요가있다. 그러나 User 인스턴스를 저장하면 신호로 호출되는 함수를 통해 또 다른 Profile이 생성됩니다.

오류가 발생하므로 방금 만든 Profile 개체를 가져올 수 없습니다. 어떤 충고?

업데이트 : 나는 그것이 저장 될 createUserProfile 방법에 signup 방법에 변수 extra_param을받을 수 있나요 어떻게

def createUserProfile(sender, instance, created, **kwargs): 
if created: 
    profile, created = Profile.objects.get_or_create(user=instance) 
    if extra_param: 
     profile.extra_param = extra_param 
    profile.save() 

post_save.connect(createUserProfile, sender=User) 

def signup(request): 
    ... 
    extra_param = 'param' 
    user.save() 

: 여기

이 가능한 상황의 예입니다 Profile 개체의 일부로?

+1

+1. 나는 이것에 대한 답을 알고 싶다. – PeanutButterJelly

답변

2

이 당신을 위해 작동하지 않는 이유 : 프로파일에 매개 변수를 전달하는 것은 전혀 문제가되지 않습니다?

user = User(...) 
user.save() 
# profile has been created transparently by post_save event 
profile = user.profile 
profile.extra_stuff = '...' 
profile.save() 

당신이 매개 변수는 이벤트 가능한 악에 통과에 집착하는 경우 : 코드를 읽을 사람들이 아무 생각이 무엇인지 그 _evil_extra_args가있는 도대체하고 있기 때문에

user = User() 
user._evil_extra_args = { ... } 
user.save() 

In event: 
extra_args = getattr(user, '_evil_extra_args', False) 

그것은 악 어떻게 작동합니까?

+3

첫 번째 것은 일종의 동시성 오류를 제공하기 때문에 결국 악의 옵션을 사용했습니다 (db 객체는 'save()'이벤트에서 잠겨 있습니다. 윤곽). –

0

지연 post_save은 (사용자가 entirely disconnect it을 원하지 않는 한) 불가능합니다. 그러나 어느 것도 필요하지 않습니다.

class UserProfile(models.Model): 
    user = models.ForeignKey(User) 
    other = models.SomeField() 

def create_user_profile(sender, instance, created, other_param=None, **kwargs): 
    if created: 
     profile, created = UserProfile.objects.get_or_create(user=instance) 
     profile.other(other_param) # or whatever 
     profile.save() 

post_save.connect(create_user_profile, sender=User, other_param=p) 
+0

그 매개 변수를 하나의 경우에만 보내고,'post_save.connect'는'User' 객체 자체를 만드는 함수가 아닌 다른 곳에 정의되어 있다면 어떨까요? 어떻게 작동할까요? –

+0

그냥 기본 값을 지정하십시오 ... (편집 된 답변) –

+0

저는 우리 중 한 명이 다른 사람들을 오해하고 있다고 생각합니다. 그래서 문제를 명확하게 설명 할 수있는 예제를 제 질문에 추가했습니다. –

관련 문제