2009-03-28 6 views
1

어떻게 동적으로 사용자 정의 필드를 추가합니까? 는 그 노력하고있어,하지만 난 DB를 동기화 할 때 필드는 데이터베이스에 삽입되지 않습니다동적으로 모델에 사용자 정의 필드 추가

#It use as register(MyModel) 
def register(model, attr="my_attr"): 

    if model in registry: 
     raise AlreadyRegistered(
      _('The model %s has already been registered.') % model.__name__) 

    registry.append(model) 
    setattr(model, attr, MyField()) 

    MyField().contribute_to_class(model, attr) 

#MyField.contribute_to_class 
def contribute_to_class(self, cls, name): 
    super(MyField, self).contribute_to_class(cls, name) 

    setattr(cls, self.name, self) 
    cls.add_to_class('%s_manager' % name, MyDescriptor()) 

    signals.post_save.connect(self._save, cls, True) 
+0

**이 가이드에 관심이있을 수 있습니다. ** http://stackoverflow.com/q/7933596/497056 –

답변

3

당신은 아마 할 수없는 장고의 내부 해킹없이. 클래스 구조로되어있는

class MyModel(models.Model): 
    my_filed = models.CharField(...) 

# Here, class construction is complete and your class has a _meta member. 
# If you want, you can check it out in the interactive shell. 
meta = MyModel._meta 

가 완료된 후, 예를 들어, 다음 syncdb 명령은 django.db.models.Model 기본 클래스의 메타 클래스를 통해 클래스의 건설 시간에 생성됩니다 만들 수있는 필드의 목록을 얻으려면 각 모델에 대한 메타 개체를 검사 DEDENT 다음에 class 문 다음에 메타 오브젝트는 고정되어 있으며 (모델 클래스 수정에 영향을받지 않음) 동적 필드를 추가하기 위해 메타를 해킹해야합니다 (물론 가능합니다). 하지만 여기에 내부 객체가 있기 때문에 장래 앱이 장고와 호환되지 않을 수 있습니다.

나머지 질문은 다음과 같습니다. 왜 그렇게하고 싶습니까? 데이터베이스 테이블은 대개 앱을 배포 할 때 한 번만 생성되므로 모델은 일종의 "정적"입니다.

+0

+1 장고 메타 클래스를 참조하십시오. 장고 모델의 메타 클래스의 하위 클래스 인 자신의 모델 메타 클래스를 작성하여이 작업을 수행하는 것이 가능합니다. 사실이 방법은 과거에 모델 상속의 부족을 해결하는 방법이었습니다. 이제 우리는 진정한 모델 상속을 얻었습니다. 아마도 더 좋은 방법 일 것입니다. –

0

나는 똑같은 것을 찾고 있었고 원시 SQL에 정착해야했습니다. SQLAlchemy와 같은 것을 사용할 수는 있지만.

관련 문제