2015-01-26 68 views
0

嗨也許有人可以指出我的方向是正確的,我通過Tango和Django學習Django,並且我也跟着官方的Django教程以及爲購買訂單創建我自己的Django應用程序。Django傳遞外鍵來查看

我需要了解如何訪問另一個模型的外鍵詳細信息並使用表單進行保存。基本上我的應用程序有訂單和供應商創建訂單時我可以得到供應商的外鍵選項出現在窗體上,但是當我保存它時,我也想將suppier_name保存到訂單表中,目前它只保存supplier_id,我已經通過很多不同場景的例子進行了搜索,但不能理解它謝謝。

view.py

def add_order(request): 
    if request.method == 'POST': 
     form = OrderForm(request.POST) 
     if form.is_valid(): 
      form.save(commit=True) 
      return orders(request) 
     else: 
      print(form.errors) 
    else: 
     form = OrderForm() 

    context_dict = {'form':form} 

    return render(
     request, 
     'purchaseorders/add_order.html', 
     context_dict 
    ) 

model.py

# Create your models here. 

class Supplier(models.Model): 
    supplier_code = models.CharField(max_length=10) 
    supplier_name = models.CharField(
     max_length=100, 
     unique=True 
    ) 
    supplier_email = models.EmailField(max_length=100) 
    supplier_website = models.URLField(max_length=100) 
    slug = models.SlugField(unique=True) 

    def save(self, *args, **kwargs): 
     self.slug = slugify(self.supplier_name) 
     super(Supplier,self).save(*args, **kwargs) 

    def __unicode__(self): 
     return self.supplier_name 

    def __str__(self): 
     return self.supplier_name 

    class Meta: 
     verbose_name_plural = "Suppliers" 


class Order(models.Model): 
    supplier = models.ForeignKey(Supplier) 
    po_number = models.IntegerField(default=0) 
    ordered_by = models.CharField(max_length=50) 
    order_date = models.DateTimeField() 
    supplier_name = models.CharField(max_length=50) 
    net_value = models.DecimalField(
     decimal_places=2, 
     max_digits=10 
    ) 

    class Meta: 
     verbose_name_plural = "Orders" 

    def __unicode__(self): 
     return self.po_number 

forms.py

from django import forms 
from PurchaseOrders.models import Supplier, Order 

class SupplierForm(forms.ModelForm): 
    supplier_code = forms.CharField(
     max_length=10, 
     help_text="Please enter a unique code" 
    ) 
    supplier_name = forms.CharField(
     max_length=100, 
     help_text="Please enter the Suppliers full name" 
    ) 
    supplier_email = forms.EmailField(
     max_length=100, 
     help_text="Please enter a email address" 
    ) 
    supplier_website = forms.URLField(
     max_length=100, 
     help_text="Please enter a website" 
    ) 
    slug = forms.CharField(
     widget=forms.HiddenInput(), 
     required=False 
    ) 

# an inline class to provide additional information on the form 
    class Meta: 
     # provide an association between the ModelForm and model 
     model = Supplier 
     fields = (
      'supplier_code', 'supplier_name', 
      'supplier_email', 'supplier_website' 
     ) 

class OrderForm(forms.ModelForm): 
    #list all form details except the Foreignkey connection 
    po_number = forms.IntegerField(
     help_text="please enter a PO Number" 
    ) 
    ordered_by = forms.CharField(
     max_length=50, 
     help_text="please enter your name" 
    ) 
    order_date = forms.DateTimeField(
     help_text="please enter a date of order" 
    ) 
    #supplier_name = forms.ModelChoiceField(
     queryset=Supplier.objects.all() 
    ) 
    net_value = forms.DecimalField(
     decimal_places=2, 
     max_digits=10, 
     help_text="please enter a net amount" 
    ) 

    class Meta: 
     # provide an association between the ModelForm and model 
     model = Order 

HTML

{% load staticfiles %} <!-- New line --> 

<html> 
    <head> 
     <title>Purchase Orders</title> 
    </head> 

    <body> 
    <img src="{% static "purchaseorders/images/po_icon.png" %}" 
    alt="PO icon" /> 
    <h1>Add a Order</h1> 

    <form id="order_form" method="post" 
    action="/PurchaseOrders/add_order/{{ supplier }}"> 

     {% csrf_token %} 
     {% for hidden in form.hidden_fields %} 
      {{ hidden }} 
     {% endfor %} 
     <ul style="list-style-type:none "> 
     {% for field in form.visible_fields %} 
      <li></li> 
      {{ field.errors }} 
      {{ field.help_text }} 
      <li>{{ field }}</li> 
     {% endfor %} 
     </ul> 
     <input type="submit" name="submit" value="Add Order" /> 
    </form> 
</body> 
</html> 
+0

爲什麼要這樣做?這是不必要的數據重複。訂單始終可以通過外鍵訪問供應商名稱,因此沒有意義保存該名稱的單獨副本。 – 2015-01-26 20:22:30

+0

葉有效點我想我只是想了解如果我想如果我可以做,然後像你指出意識到沒有必要。 – Paulmc 2015-01-26 20:24:02

+0

我的另一個想法是,如果我使用另一個字段從供應商模型我怎麼也可以找到基於該字段的ID然後保存它,當我試圖這樣做,我會得到外鍵完整性null約束錯誤, – Paulmc 2015-01-26 20:25:35

回答

0

首先的問題是問的,你可以在模型中的保存捕獲此數據()方法:

class Order(models.Model): 
    [...] 
    def save(self, *args, **kw): 
     if self.supplier_id is not None: 
      self.supplier_name = self.supplier.supplier_name 
     super(Order, self).save(*args, **kw) 

然而,儘管有一些情況下,上述可能是正確的(例如,如果供應商名稱預計會改變),通過現有關係簡單訪問相關領域更爲典型,例如:

myorder.supplier.supplier_name 
+0

謝謝我現在在我的模板中顯示了myorder.supplier.supplier_name顯示,我明白我的更好的答案。 – Paulmc 2015-01-27 14:33:26