Skip to main content
 首页 » 编程设计

python之OneToThree django模型

2025年02月15日34Leo_wl

我有一个包含一些联系人数据(邮件、地址、姓名等)的经典模型,以及一个应该链接到三个联系人(管理员、所有者、技术人员)的模型。例如,联系人可以注册为管理员和技术人员。

class Contact(django.db.models.Model): 
  user = models.OneToOneField(User) 
  city = models.CharField(max_length=255, blank=True) 
  country = models.CharField(max_length=2, blank=True) 
  email = models.EmailField(max_length=255, blank=True) 
  first_name = models.CharField(max_length=255, blank=True) 
  family_name = models.CharField(max_length=255, blank=True) 
  phone = models.CharField(max_length=255, blank=True) 
 
 
class Product(... Some parents) 
  name = models.CharField(max_length=255) 
  contacts ? 

我不知道如何将 3 个联系人链接到我的其他模型...并生成一个包含已存在的查询集的表单。

一些建议? 谢谢

请您参考如下方法:

只使用外键 示例:

class Product(... Some parents) 
  name = models.CharField(max_length=255) 
  admin = models.ForeignKey(Contact, related_name="admins") 
  owner = models.ForeignKey(Contact, related_name="owners") 
  tech = models.ForeignKey(Contact, related_name="techs") 

如果要生成表单,请使用模型表单

class MyForm(forms.ModelForm): 
    class Meta: 
         model=Product 

选择的小部件将自动填充

编辑:以人性化的方式显示您的联系人使用

class Contact(django.db.models.Model): 
    <usual stuff> 
    def __unicode__(self): 
        return u"%s" % self.firstname  #  or any field you wish  

参见 https://docs.djangoproject.com/en/1.10/ref/models/instances/#str 如果你使用 python 3 用 str 替换 unicode