1

我有一个由两个模型组成的记录保存系统。一个模型创建一个保留页面,另一个模型创建单独的条目......

class RecordEntry(models.Model):
    client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
    job_number = models.CharField(max_length=30, unique=False, blank=False, null=False)
    cell_number = models.CharField(max_length=4, unique=False, blank=True, null=True)
    entry_title = models.CharField(max_length=64, unique=False, blank=True, null=True)
    date = models.DateField(("Date"), default=datetime.date.today)
    attachment = models.FileField(upload_to=content_file_name, blank=True, null=True)
    ...     

class RecordPage(models.Model):
    client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
    job_number = models.CharField(max_length=30, unique=True, blank=False, null=False)
    job_name = models.CharField(max_length=64, unique=False, blank=False, null=False)
    create_date = models.DateField(("Date"), default=datetime.date.today)
    contact = models.ForeignKey(UserProfile)
    entry = models.ForeignKey(RecordEntry, blank=True, null=True)
    ...

…页面可能是#211211,单个条目可能是#211211-01、#211211-02、#211211-03

为简单起见,我使用 admin 中呈现的表单来创建页面。这很方便,因为管理员给了我“加号”图标,让我可以即时创建和添加条目。我的问题是,我希望能够根据需要向页面添加尽可能多的“条目”。我的意思是,要在表单上获取多个“输入”字段,我可以执行以下操作:

class RecordPage(models.Model):
    client = models.CharField(max_length=50, choices=CLIENT_CHOICES)
    job_number = models.CharField(max_length=30, unique=True, blank=False, null=False)
    job_name = models.CharField(max_length=64, unique=False, blank=False, null=False)
    create_date = models.DateField(("Date"), default=datetime.date.today)
    contact = models.ForeignKey(UserProfile)
    entry = models.ForeignKey(RecordEntry, blank=True, null=True)
    entry2 = models.ForeignKey(RecordEntry, related_name='+', blank=True, null=True)
    entry3 = models.ForeignKey(RecordEntry, related_name='+', blank=True, null=True)
    entry4 = models.ForeignKey(RecordEntry, related_name='+', blank=True, null=True)
    entry5 = models.ForeignKey(RecordEntry, related_name='+', blank=True, null=True)
    entry6 = models.ForeignKey(RecordEntry, related_name='+', blank=True, null=True)
    entry7 = models.ForeignKey(RecordEntry, related_name='+', blank=True, null=True)
    and so on…

但必须有更好的方法,对吧?

4

1 回答 1

0

为什么不在这里使用 ManyToManyField

entry = models.ManyToManyField('RecordEntry', related_name='pages')

并且 Django admin 将自动为您提供添加新行的能力。

于 2012-07-22T13:24:39.677 回答