Django形式的模型模型

时间:2014-12-21 23:49:51

标签: django django-models django-forms

我有以下模型来定义客户。我认为可重用性将地址和“人”字段分成单独的模型。由于Customer包含一个Person,而Person又包含一个Address,如何为Customer创建CreateView?不太了解如何使用像inline_formset这样的东西来实现我想要的东西。

models.py:

import localflavor.us.models as us_models
from django.db import models
from datetime import date

class Address(models.Model):
    address1 = models.CharField(max_length=100)
    house_number = models.CharField(max_length=10, blank=True)
    address2 = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=50)
    state = us_models.USStateField()
    zip = models.CharField(max_length=5)


class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    creation_date = models.DateTimeField('date created')
    home_phone = us_models.PhoneNumberField()
    work_phone = us_models.PhoneNumberField(blank=True)
    cell_phone = us_models.PhoneNumberField(blank=True)
    email = models.EmailField(blank=True)
    address = models.OneToOneField(Address, primary_key=True)


class Customer(models.Model):
    person = models.OneToOneField(Person, primary_key=True, default=None)
    creation_date = models.DateTimeField('date created', auto_now_add=True)

1 个答案:

答案 0 :(得分:1)

对于您的地址字段,它非常简单,您可能希望look at using an inline formset。它需要相当多的代码,但是教程非常简单。

但是,对于Person / Customer问题,请不要忘记模型首先是Python对象,因此您可以使用大量的OOP继承原则。如果Customer Person文档:

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    # ... fields trimmed ...
    address = models.OneToOneField(Address, primary_key=True)

class Customer(person):
    creation_date = models.DateTimeField('date created', auto_now_add=True)

在这里,我们已经清楚地定义了这种关系,并且在幕后关系得到了关注。但是,一个重要的警告,名称和加法器仍在Person表中,因此对Person的查询也会返回Customer

另一种选择是using an abstract class,如下所示:

class Person(models.Model):
    class Meta:
        abstract = True
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    # ... fields trimmed ...
    address = models.OneToOneField(Address, primary_key=True)

class Customer(person):
    creation_date = models.DateTimeField('date created', auto_now_add=True)
class Retailer(person):
    creation_date = models.DateTimeField('date created', auto_now_add=True)

现在,Person对象不会获得数据库表,只能通过继承来使用 - 所以我们可以查询CustomerRetailer s,但不能查询{{1 }}第