我如何正确编写这个django模型关系?

时间:2017-04-08 21:33:31

标签: python django django-models orm django-admin

class A:
   a = models.CharField()

class B:
   aa = models.ForeignKey(A) # refering A.a
   b = models.CharField()


class C:
   c = models.CharField()
   aa = models.ForeignKey(B) # refering B.aa
   bb = models.ForeignKey(B) # refering B.b

为简单起见,我们说A包含三个条目:u,v和w 和B包含:(u,x),(u,y),(u,z),(v,x),(v,k)和(w,y)。

现在我希望管理员能够创建C的实例,首先他输入字段c的值,然后选择(u,v,w)中的任何一个字段aa。

选择u - > x,y,z应该出现以供选择bb,

选择v - >应出现x和k以供选择bb,

选择w - >只有x才能出现以供选择bb,

不幸的是,经过多次尝试后,我无法正确编写完全按照我打算做的外键关系。

修改

 # myapp/models.py
 from django.db import models
 from smart_selects.db_fields import ChainedForeignKey


class Continent(models.Model):
name = models.CharField(max_length=20)

def __str__(self):
    return self.name

class Country(models.Model):
name = models.CharField(max_length=20)
continent = models.ForeignKey(Continent)

def __str__(self):
    return self.name


class Location(models.Model):
newcontinent = models.ForeignKey(Continent)
newcountry = ChainedForeignKey(
    Country, # the model where you're populating your countries from
    chained_field="newcontinent", # the field on your own model that this field links to
    chained_model_field="continent", # the field on Country that corresponds to newcontinent
   # show_all=False, # only shows the countries that correspond to the selected continent in newcontinent
)

my_address = models.CharField(max_length=20)


#myapp/forms.py
from myapp.models import Location
from django.forms import ModelForm

class LocationForm(ModelForm):
class Meta:
    model = Location
    fields = ['newcontinent', 'newcountry', 'my_address']


#myapp/templates/myapp/addLocationForm.html   
{% extends 'registration/base.html' %}

{% block title %}Add a new location{% endblock %}

{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
 <button type="submit"> Post </button>
  </form>
{% endblock %}

#myapp/views.py
def addlocation(request):
if request.POST == "POST":
    form = LocationForm()
    if form.is_valid():
       form.save()
       return redirect('home')
else:
    form = LocationForm()
    return render(request, 'myapp/addLocationForm.html', { 'form': form})


#urls.py
 url(r'^location/add/$', core_views.addlocation,name='add-location'),

上述代码不起作用。我可以选择由管理员添加的大陆。但是,没有选择国家的选项。

2 个答案:

答案 0 :(得分:0)

Your question is bit unclear, but I think what you want can be achieved using django-smart-selects and its chained foreign key.

Just have a look here go through it and then try it on your project.

I am quite sure it will work for you.

答案 1 :(得分:0)

如果智能选择在管理页面中有效,那么在您的html文件中包含以下内容,它将起作用。订单很重要。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js</script>
    <script src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script>
    <script src="{% static 'smart-selects/admin/js/chainedm2m.js' %}"></script>