2014-01-18 72 views
0

我有两个应用程序。一个customer和另一个xyz。在我的xyz应用程序中,我有4个模型。 Country,States,Cities & Shops。在我的客户应用程序中,我有一个型号CustomersDjango模板中的多个外键set_all

我的客户模型

class Customers(models.Model): 
    shop = models.ForeignKey(Shops) 
    user = models.ForeignKey(User) 
    uuid = UUIDField(auto=True) 
    name = models.CharField(max_length=200) 
    country = models.ForeignKey(Country) 
    state = models.ForeignKey(States) 
    city = models.ForeignKey(Cities) 

我查看

def edit_customer(request,uuid): 
    current_customer = Customers.objects.filter(uuid=uuid,deleted=0) 
    return render_to_response('customers/edit_customer.html',{'current_customer':current_customer},context_instance=RequestContext(request)) 

我在模板尝试这个。但没有发现。

{% for customer in current_customer %} 

    {% for cn in customer.country_set.all %} 
     <li>{{ cn.name }} </li> 
     <li>{{ cn.id }} </li> 
    {% endfor %} 

    {% for st in customer.states_set.all %} 
     <li>{{ st.name }} </li> 
     <li>{{ st.id }} </li> 
    {% endfor %} 

    {% for ct in customer.cities_set.all %} 
     <li>{{ ct.name }} </li> 
     <li>{{ ct.id }} </li> 
    {% endfor %} 

{% endfor %} 

什么是正确的方法?

回答

1

你正试图反过来这样做。正如django文档所述:

Django还为关系的“其他”一方创建API访问器 - 从相关模型到定义关系的模型的链接。例如,Blog对象b可以通过entry_set属性访问所有相关Entry对象的列表:b.entry_set.all()。

通知the "other" side

所以在你的情况下,你可以做state.customer_set.all()。但看看你试图达到什么我猜你正在使用错误的字段类型,如果你想customer能够选择多个位置,你应该使用ManyToManyField

class Customer(models.Model): 
    shop = models.ForeignKey(Shops) 
    user = models.ForeignKey(User) 
    uuid = UUIDField(auto=True) 
    name = models.CharField(max_length=200) 
    countries = models.ManyToManyField(Country) 
    states = models.ManyToManyField(States) 
    cities = models.ManyToManyField(Cities) 

,然后你可以这样做customer.countries.all()customer.states.all()customer.cities.all()

更新:将数据添加到ManyToManyField

将数据添加到ManyToManyField的,你可以这样做:

customer = Customer(shop_id=shop_id, name=name) 
customer.save() 

# Add ManyToMany's 
custome.states.add(state) 
customer.cities.add(cities) 
customer.countries.add(country) 

我还建议你通过django文档查看ManyToManyFields

+0

我正在插入这样的客户数据。现在我把我的领域变成了许多东西。所以我不能插入countr,州和城市这样的。如何在customers_countries表中插入客户数据。 c = Customers(shop_id = shop_id,name = name,country = country,state = state,city = city) c.save() –

+0

查看更新后的答案。 – Amyth