如果我更改另一个字段,如何更改DjangoAdmin字段中的选项?

时间:2017-01-11 14:59:43

标签: python django admin models

我正在为酒店创建一个数据库,我希望能够在上一个字段中选择与所选酒店相关的所有季节(FK)字段。

class PriceTable(models.Model):
    client = models.ForeignKey(Cliente, on_delete=models.CASCADE)
    year = models.ForeignKey(Ano, on_delete=models.CASCADE)
    hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE)
    season_price = models.ForeignKey(SeasonPrice, on_delete=models.CASCADE)

class SeasonPrice(models.Model):
    season = models.ForeignKey(Season, on_delete=models.CASCADE)

class Season(models.Model):
    name = models.CharField(max_length=200)
    date_in = models.DateField()
    date_end = models.DateField()
    hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE)

在django管理页面中,我如何在season_price中列出所有拥有我所选择的酒店外键的季节? 这是一张图片,可以更好地理解我想要完成的内容:Django admin explanation

1 个答案:

答案 0 :(得分:0)

通常,我总是使用JQuery来解决这类问题。这是一个例子,这是一个简单的例子,你必须改变必要的部分。

说明

Select a user in the page, and the article will change to the articles belong to the selected user.

urls.py

from TestDjango.testdb import testdb, getArticlesByUser
urlpatterns = [
    ......
    url(r'^testdb/$', testdb, name='testdb'),
    url(r'^getarticles/$', getArticlesByUser, name='get_art'),
    ......
]

testdb.py

from django.shortcuts import render
from Articles.models import Articles
from Users.models import Users

def testdb(request):
    context = {
        'users': Users.objects.all(),
    }
    return render(request, "Users/list.html", context)


def getArticlesByUser(request):
    # get parameters from page - Users/list.html
    user_id = request.GET.get('user_id', None)

    # get data from database by using "user_id"
    list_articles = Articles.objects.filter(user_id=user_id)

    str_alltitle = ""
    for item in list_articles:
        str_alltitle += '<option value="' + str(item.id) + '"> ' + item.title + ' </option> '

    # return a json response to the html
    from django.http import JsonResponse
    return JsonResponse({'articles': str_alltitle})

list.html

{% extends "base.html" %}

{% block title %}
    List Articles By User ID - User
{% endblock %}

{% block mainbody %}
<p>
    <span>User:</span>
    <select id="user" name="user_id">
        <option value="">---Empty---</option>
        {% for user in users %}
            <option value="{{ user.id }}" > {{ user.email }} </option>
        {% endfor %}
    </select>
</p>
<p>
    <span>Articles:</span>
    <select id="article" name="article_id"></select>
</p>
{% endblock %}

{% block scriptsection %}
<script type="text/javascript">
$('#user').bind('change', function () {

   $.ajax({
      url: '/getarticles/?user_id='+ this.value,
      type: 'GET',
      success: function (json) {
          $('#article').html(json['articles'])
      }
  });
});

</script>
{% endblock %}

这在我的电脑上运行,我使用的是python 3.4和Django 1.10.4!