如果您使用的是ForeignKey,該怎麼辦?
此代碼(未經測試和演示)假定存在系統範圍的一組自定義字段。爲了使它成爲用戶特定的,你需要在類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)
你可能想澄清你的目標。您是否想簡單地將任意元數據與這些用戶關聯起來,還是需要按特定字段查找用戶? – 2009-09-23 00:20:58
您可能會尋找這個參考:http://stackoverflow.com/a/7934577/497056 – 2012-02-19 13:31:08