Django形成目标外键

时间:2014-10-26 18:21:26

标签: django django-models django-forms

我有一张提交订单的表格。多个项目已附加到目录对象,我希望表单下拉列表包含附加到外键的所有项目的选项,而不是外键目录名称可用。我知道如何使用相关名称在视图中访问这些,这可能在表单中吗?

这是我目前的表格:

from django import forms

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, ButtonHolder, Submit

from . import models

class OrderListForm(forms.ModelForm):
    class Meta:
        fields = ('order_lines',)
        model = models.Order

    def __init__(self, *args, **kwargs):
        super(OrderListForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            'order_lines',
            ButtonHolder(
                Submit('create', 'Create')

            )


        )

这是我的模特:

class Catalog(models.Model):
    products = models.CharField(max_length=200)

    def __unicode__(self):
        return self.products

class Issue(models.Model):
    catalog = models.ForeignKey(Catalog, related_name='issue_products')
    Volume = models.DecimalField(max_digits=3, decimal_places=1)

    def __unicode__(self):
        return unicode(self.catalog)


class Annual(models.Model):
    catalog = models.ForeignKey(Catalog, related_name='annual_products')
    year_id = models.IntegerField(max_length=4)
    start_date = models.CharField(max_length=6)
    end_date = models.CharField(max_length=6)
    def __unicode__(self):
        return unicode(self.year_id)


class Annual_Issue(models.Model):
    annual_id = models.ForeignKey(Annual, related_name='annual_ids')
    issue_id = models.ForeignKey(Issue, related_name='issues')
    def __unicode__(self):
        return self.annual_id


class Article(models.Model):
    catalog = models.ForeignKey(Catalog, related_name='article_products')
    title = models.CharField(max_length=200)
    abstract = models.TextField(max_length=1000, blank=True)
    full_text = models.TextField(blank=True)
    proquest_link = models.CharField(max_length=200, blank=True, null=True)
    ebsco_link = models.CharField(max_length=200, blank=True, null=True)

    def __unicode__(self):
        return self.title


class Order(models.Model):
    user = models.ForeignKey(User, related_name='who_ordered')
    order_lines = models.ForeignKey(Issue, related_name='items_ordered')

1 个答案:

答案 0 :(得分:0)

您可以使用以下方式访问同一目录中的所有年度和文章:

c = Catalog.objects.get(....
c.article_products_set.all()
c.annual_products_set.all()