如何创建UserProfile字段,该字段是用户字段的别名?

时间:2015-01-13 16:33:02

标签: python django django-users

我想从UserProfile访问User model的first_name,last_name和email字段,就好像它们是UserProfile自己的字段一样。

class Person(models.Model):
    user = models.OneToOneField(User)
    name = #ModelField which refers to user.first_name
    surname = #ModelField which refers to user.last_name
    email = #ModelField which refers to user.email
    birth_date = models.DateField(null=True, blank=True)
    #and other fields

我可以使用独立的姓名,姓氏,电子邮件,字段,但这会导致与用户字段重复数据。

UPD

我希望namesurnameemail属于某种Field类型(作为birth_date)并修改这些字段以等同修改相应的用户字段(属性)行为如下所示)。我需要这个,因为我希望这三个字段在管理界面中可以使用,或者与ModelForm中的“原生”字段同等地进行处理。

更新解决方案。不是很花哨,但在这里它对我有用:

class Person(models.Model):
    user = models.OneToOneField(User)
    #and also some char, text fields

    @property
    def name(self):
        return self.user.first_name
    @name.setter
    def name(self, value):
        self.user.first_name = value

    #and by analogy surname and email properties


class PersonForm(ModelForm):
    class Meta:
        model = Person
        exclude = ('user',)

    name = forms.CharField(max_length=100, required=False)
    surname = forms.CharField(max_length=100, required=False)
    email = forms.EmailField(required=False)

    #no make fields filled with User data on form load
    def __init__(self, *args, **kwargs):
    if 'instance' in kwargs:
        instance = kwargs['instance']
        initial = kwargs.get('initial', {})
        initial['name'] = instance.name
        initial['surname'] = instance.surname
        initial['email'] = instance.email
        kwargs['initial'] = initial
    super(PersonForm, self).__init__(*args, **kwargs)

    # to save form data to User model when commit
    def save(self, commit=True):
        instance = super(PersonForm, self).save(commit)  
        user = instance.user
        user.first_name = self.cleaned_data['name']
        user.last_name = self.cleaned_data['surname']
        user.email = self.cleaned_data['email']
        user.save()
        return instance

class PersonAdmin(admin.ModelAdmin):
    fields = ['name', 'surname', 'email', 'and_others']

    form = PersonForm

admin.site.register(Person, PersonAdmin)

2 个答案:

答案 0 :(得分:1)

class Person(models.Model):
    user = models.OneToOneField(User)
    @property
    def name(self):
        return self.user.first_name
    @property
    def surname(self):
        return self.user.last_name

答案 1 :(得分:1)

如果您想要的是直接访问user.first_name,user.last_name等...作为Person的属性,您可以将名称,姓氏等属性添加到Person模型,而不是字段:< / p>

class Person(models.Model):
    user = models.OneToOneField(User)
    birth_date = models.DateField(null=True, blank=True)
    #and other fields

    @property
    def name(self):
        return self.user.first_name

    @property
    def surname(self):
        return self.user.last_name
    ....