python - Django 2.1.7 : Populate Child field with Selected Parent Attributes in Product Model

标签 python django

我有 3 个模型:类别子类别产品

SubCategory 通过 ForeignkeyCategory 相关,ProductCategorySubcategory 通过 ForeignKey

What My Db looks like:

Category: Kids
    -->SubCategory: Beanies
Category: Men
    -->SubCategory: Hoodies

现在,当我想添加产品并选择 Kids 时,在 Product 管理页面中,我只希望显示相关的子类别。

我尝试过的:

  1. 使用 formfield_for_foreignkey 但我似乎无法理解它是如何工作的。

  2. 我遇到了这个问题 Django Admin Show / Hide Fields If Specific Value Is Selected In A Dropdown但我认为它更多的是与领域相关,而不是与值(value)相关。

我在网上找到的建议:

  • 使用 ajax 获取子类别并将它们插入子字段。

我的模型:

class Category(models.Model):
    name = models.CharField(max_length=250, db_index=True, unique=True)
    slug = models.SlugField(max_length=250, db_index=True, unique=True)

class SubCategory(models.Model):
    parent = models.ForeignKey(Category, on_delete=models.CASCADE)
    name = models.CharField(max_length=250, db_index=True)
    slug = models.SlugField(max_length=250, db_index=True)

class Product(models.Model):  
    parent = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category")
    child = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
    name = models.CharField(max_length=250, unique=True, db_index=True)
    slug = models.SlugField(max_length=250, unique=True, db_index=True)

我的管理模型:

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = [
        'name', 'slug'
    ]

@admin.register(SubCategory)
class SubCategoryAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug':('name',)}
    list_display = [
        'name', 'slug', 'parent',
    ]
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = [
        'name', 'slug', 'child', 
    ]
    prepopulated_fields = {'slug':('name',)}
    list_per_page = 20

    class Media:
        js = ('javascript/hide_child_if_parent_is_none.js', )

最佳答案

我用 Django Rest Framework 修复了它& AJAX ,这是一次有趣的经历。这是代码

SubCategory模型我已经编辑了我的 parent通过添加 related_name 字段并将其从 Product.parent 中删除

parent = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="children")

我的序列化程序:

from rest_framework import serializers
from catalogue.models import Category, SubCategory
from drf_writable_nested import WritableNestedModelSerializer
# Create your serializers here.

class SubCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = SubCategory
        fields = ('id', 'name',)

class CategorySerializer(WritableNestedModelSerializer):
    children = SubCategorySerializer(many=True)
    class Meta:
        model = Category
        fields = ('id', 'name', 'children')

我的 AJAX调用:

(function($) {
    $(function() {
        var selectField = $('#id_parent'),verified = $('#id_child');

        function toggleVerified(value) {
            if (value) {
                verified.show();
                console.log(value);
            } else {
                verified.hide();
            };
        };

        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        };
        var csrftoken = getCookie('csrftoken');

        function plugOptions(array, target){
            var children = array.children;
            //console.log(children);
            target.empty();
            target.append(new Option("---------", false))
            $.each(children, function(key){
                target.append(new Option(children[key].name, children[key].id));
            });
        };

        // show/hide on load based on pervious value of selectField
        toggleVerified(selectField.val());

        // show/hide on change
        selectField.change(function() {
            toggleVerified($(this).val());

            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            });
            $.ajax({
                type: 'GET',
                url: '/my_api/categories/'+$(this).val(),
                contentType: "application/json; charset=utf-8",
                success: function(resp) {
                    console.log("success"),
                    plugOptions(resp, verified)
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(jqXHR),
                    console.log(textStatus),
                    console.log(errorThrown)
               }
            });
        });
    });
})(django.jQuery);

关于python - Django 2.1.7 : Populate Child field with Selected Parent Attributes in Product Model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55927922/

相关文章:

python - 在 python matplotlib 中使 Label、bbox 或 axes.text 的边框与 Graph 的脊柱齐平

python - 如何访问 pandas 中的多索引级别?

python - 如何从模型属性填充 django 管理表单?

python - request.POST 中的每个值都是一个列表

Django + WordPress : Integrating user login

python - 将变量从 views.py 传递到 forms.py 导致表单提交时出错

python - 有没有办法缩短我的代码,这样我就不必每次使用 turtle 模块中的函数时都写 "turtle."?

python - Pyinstaller 与 Pillow 的问题

python - 如果 python 运行文件 "line after line"它如何在定义之前使用函数?

python - Pytest Django 发现 Fixture 但在运行时显示 "Not Found"