2009-09-22 5 views
2

좋아, 여러 가지 모델, 즉 계정, 연락처 등 각각 다른 필드 집합으로 장고 응용 프로그램에서 작업하고 있습니다. 내 각 사용자가 기존 필드 외에 자신의 필드를 정의 할 수 있어야합니다. 많은 수의 CustomField를 보유하고 각 사용자가 사용하는 각 필드에 사용자 정의 이름을 매핑하는 것에서부터 이것을 구현하는 몇 가지 다른 방법을 보았습니다. 복잡한 매핑이나 XML/JSON 스타일 저장/사용자 정의 필드 검색을 구현하기위한 권장 사항도 있습니다.Django에서 사용자 정의 필드를 만드는 방법

제 질문은 이것입니다, 누군가가 장고 응용 프로그램에서 사용자 정의 필드를 구현 했습니까? 그렇다면 전반적인 구현 (안정성, 성능 등)에 대한 귀하의 경험은 어떻습니까?

업데이트 : 내 목표는 각 사용자가 각 레코드 유형 (계정, 연락처 등)을 n 개 생성하고 사용자 정의 데이터를 각 레코드와 연관시키는 것입니다. 예를 들어 내 사용자 중 한 명이 SSN을 각 연락처와 연결하기를 원할 수 있으므로 그가 만든 각 연락처 레코드에 대해 추가 필드를 저장해야합니다.

감사합니다.

마크

+0

목표를 명확히 할 수 있습니다. 임의의 메타 데이터를 이러한 사용자와 단순히 연관 시키거나 특정 필드를 통해 사용자를 조회해야합니까? –

+0

이 참조를 찾고 싶습니다. http://stackoverflow.com/a/7934577/497056 –

답변

3

외래 키를 사용한다면 어떨까요?

이 코드 (테스트되지 않음 및 데모 용)에는 시스템 전체에서 사용자 지정 필드 집합이 있다고 가정합니다. 사용자별로 작성하려면 CustomField 클래스에 "user = models.ForiegnKey (User)"를 추가하십시오.

class Account(models.Model): 
    name = models.CharField(max_length=75) 

    # ... 

    def get_custom_fields(self): 
     return CustomField.objects.filter(content_type=ContentType.objects.get_for_model(Account)) 
    custom_fields = property(get_fields) 

class CustomField(models.Model): 
    """ 
    A field abstract -- it describe what the field is. There are one of these 
    for each custom field the user configures. 
    """ 
    name = models.CharField(max_length=75) 
    content_type = models.ForeignKey(ContentType) 

class CustomFieldValueManager(models.Manager): 

    get_value_for_model_instance(self, model): 
     content_type = ContentType.objects.get_for_model(model) 
     return self.filter(model__content_type=content_type, model__object_id=model.pk) 


class CustomFieldValue(models.Model): 
    """ 
    A field instance -- contains the actual data. There are many of these, for 
    each value that corresponds to a CustomField for a given model. 
    """ 
    field = models.ForeignKey(CustomField, related_name='instance') 
    value = models.CharField(max_length=255) 
    model = models.GenericForeignKey() 

    objects = CustomFieldValueManager() 

# If you wanted to enumerate the custom fields and their values, it would look 
# look like so: 

account = Account.objects.get(pk=1) 
for field in account.custom_fields: 
    print field.name, field.instance.objects.get_value_for_model_instance(account) 
관련 문제