2014-12-01 22 views
0

爲每個用戶創建一個聯繫人/電話號碼列表我是一個有點新的Django和至今剛剛與簡單的數據庫/模型配置工作。但我開始遇到一些限制。我需要爲個人用戶添加聯繫人列表,只需存儲一組姓名和電話號碼即可。 但我沒有辦法做到這一點,我已經創建的UserProfile模型,除了將整個列表作爲字符串或反序列化的JSON存儲在單個字符或文本字段(yuck)之外。新延長Django的用戶配置文件,需要幫助數據庫

例如說我有模式:

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 

    #Persional Informaiton 
    height     = models.CharField(max_length=24, blank=False,null=True) 
    weight     = models.CharField(max_length=24, blank=False,null=True) 
    birthday    = models.CharField(max_length=24, blank=False,null=True) 

    ###THIS IS THE FIELD I NEED TO ADD!! 
    #Contacts 
    contact_list   = models.SomeKindOfField() #could contain either an array or JSON?? 

    class Meta: 
     managed = True 
     db_table = 'user_profiles'   

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) 

是否有這樣做的其他方式?我也想過爲每個用戶創建一個名爲「姓名」和「電話」列的表,但開始懷疑這是否會成爲一個噩夢來管理。

我正在做關於使用models.ForeignKey(用戶)一個小小的研究,但從未完全掌握它的實施。

任何指針這裏將不勝感激!謝謝。

回答

1

如果您正在尋找這樣做在一個標準的關係型數據庫的方式,有幾個選項。

  1. 添加Contact模型姓名和電話號碼屬性和一個ForeignKey到UserProfile。這可以讓你做user_profile.contact_set.all()。或者,如果您希望多個用戶能夠共享某些聯繫人,則可以使用ManyToMany而不是FK。
  2. 如果你真的想要的電話號碼與用戶或用戶配置文件記錄進行關聯,使用戶的聯繫人列表是其他用戶,而不是僅僅什錦電話號碼和姓名,你可以在phone_number屬性添加到您的用戶配置模式。然後contact_list = models.ManyToManyField('self')。見文檔:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.symmetrical

另外,如果你不想擔心多個模型的關係和你使用的是Postgres,您可以使用hstore,它允許你存儲詞典字段。有關如何工作的實際文檔,請參閱https://github.com/djangonauts/django-hstore

+0

@ Gman-O,我沒有代表評論你的答案,womp。但很高興你能工作! Re:最佳實踐/我的觀點,'managed'和'db_table'屬性通常保持默認。用Django 1。5+你不再需要UserProfile模型,你可以[創建一個自定義的'User'模型](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substitution-a-custom-user代替)。但是,嘿,如果它全部正常工作...... – baylee 2014-12-02 09:11:09

0

非常感謝baylee對這個偉大的解釋。我能夠啓動並運行一些東西。我不完全確定這是否會被認爲是最佳做法?而且我也不確定這個方案是否存在安全漏洞或瓶頸,但它似乎在我的應用程序中運行良好。

models.py

from django.db import models 
from django.contrib.auth.models import User 

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    height     = models.CharField(max_length=24, blank=False,null=True) 
    weight     = models.CharField(max_length=24, blank=False,null=True) 
    birthday    = models.CharField(max_length=24, blank=False,null=True) 

    class Meta: 
     managed = True 
     db_table = 'user_profiles'   
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0]) 

class UserContacts(models.Model): 
    user     = models.ForeignKey(User) 
    name     = models.CharField(max_length=24, blank=False,null=True) 
    phone     = models.CharField(max_length=24, blank=False,null=True) 

    class Meta: 
     managed = True 
     db_table = 'user_contacts' 

views.py

def add_contact(request): 
    if request.user.is_authenticated(): 
     update_success = False 
     form = addContact(request.POST or None) 
     if request.method == 'POST': 
      if form.is_valid(): 
       data = form.cleaned_data 
       contact = form.save(commit=False) 
       contact.user = request.user 
       contact.save() 
       form = addContact() #return blank form so user can continue adding to db 
       update_success = True 

     return render_to_response('contact_form.html', 
            {'update_success':update_success, 
            'form':form, 
            }, 
            context_instance=RequestContext(request), 
           ) 
    else: 
     return redirect('/accounts/login/') 

forms.py

from django import forms 
#Using Crispy forms helper object and bootstrap styling 
from crispy_forms.helper import FormHelper 
from crispy_forms.layout import Submit, Layout, ButtonHolder 
from crispy_forms.bootstrap import TabHolder, Tab 
#Using Models from "project.account" app 
from accounts.models import UserContacts 

class addContact(forms.ModelForm):  
    def __init__(self, *args, **kwargs): 
     super(addContact, self).__init__(*args, **kwargs)  
     self.helper = FormHelper() 
     self.helper.form_tag = False 
     self.helper.layout = Layout(
      TabHolder(
       Tab(
        'Basic Information', 
         'name', 
         'phone', 
        ), 
      ), 
      ButtonHolder(
         Submit('Save', 'Proceed', css_class='btn btn-lg btn-default') 
         ), 
     ) 
    class Meta: 
     model = UserContacts 
     fields = ( 
        'name', 
        'phone', 
       ) 

謝謝大家!