我有 3 个模型:类别
、子类别
和产品
。
SubCategory
通过 Foreignkey
与 Category
相关,Product
与 Category
和 Subcategory
通过 ForeignKey
。
What My Db looks like:
Category: Kids
-->SubCategory: Beanies
Category: Men
-->SubCategory: Hoodies
现在,当我想添加产品并选择 Kids
时,在 Product
管理页面中,我只希望显示相关的子类别。
我尝试过的:
使用
formfield_for_foreignkey
但我似乎无法理解它是如何工作的。我遇到了这个问题 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/