django 如何将ModelMultipleChoiceField添加到模型中?

um6iljoc  于 2023-10-21  发布在  Go
关注(0)|答案(2)|浏览(156)

如何在ModelMultipleChoiceField中显示我的模型我有models.py

# Модель заказа
class ProductsSet(models.Model):
    # Название набора
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="ID")
    name = models.CharField(max_length=200)
    products_set = models.ManyToManyField('ProductsInstance', related_name='sets') 
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_date = models.DateField(null=True, blank=True)

class ProductsInstance(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid.uuid4,
                          help_text="Unique ID")
    product = models.ForeignKey('Products', on_delete=models.RESTRICT, null=True)

admin.py

@admin.register(ProductsInstance)
class ProductsInstanceAdmin(admin.ModelAdmin):
    list_display = ('product', 'price_for_client', 'borrower', 'coeff')
    list_filter = ('status','borrower',)

    fieldsets = (
        (None, {
            'fields': ('product', 'coeff', 'price_for_client', 'id')
        }),
        ('Availability', {
            'fields': ('status', 'borrower')
        }),
    )
    
@admin.register(ProductsSet)
class ProductsSetAdmin(admin.ModelAdmin):
    list_display = ('name', 'borrower', 'created_date', 'status', 'total_amount')
    fields = ['id', 'name', 'products_set', 'created_date', 'borrower', 'status', 'total_amount']
    list_filter = ['borrower','created_date','status']

我现在看起来像什么enter image description here
这就是我想要的enter image description here

bzzcjhmw

bzzcjhmw1#

以下是我的解决方案:

class ProductsSetForm(forms.ModelForm):
   
    class Meta:
        model = Group
        exclude = []
 
        products = forms.ModelMultipleChoiceField(
         queryset=ProductsInstance.objects.all(),
         required=False,
         widget=FilteredSelectMultiple('products', False)
    )

    def __init__(self, *args, **kwargs):
        super(ProductsSetForm, self).__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields['products'].initial = self.instance.products_set.all()

    def save_m2m(self):
        self.instance.products_set.set(self.cleaned_data['products'])

    def save(self, *args, **kwargs):
        self.total_amount = sum(product.price_for_client for product in self.products_set.all())
        instance = super(ProductsSetForm, self).save()
        self.save_m2m()
        return instance
    class ProductsSetAdmin(admin.ModelAdmin): 
        form = ProductsSetForm 
        list_display = ('name', 'borrower', 'created_date', 'status', 'total_amount')
        fields = ['id', 'name', 'products_set','products', 'created_date', 'borrower', 'status', 'total_amount']
        list_filter = ['borrower','created_date','status']  
    admin.site.register(ProductsSet, ProductsSetAdmin)
bkhjykvo

bkhjykvo2#

在**filter_horizontal**属性[Django-doc]中列出关系:

@admin.register(ProductsSet)
class ProductsSetAdmin(admin.ModelAdmin):
    list_display = ('name', 'borrower', 'created_date', 'status', 'total_amount')
    fields = [
        'id',
        'name',
        'products_set',
        'created_date',
        'borrower',
        'status',
        'total_amount',
    ]
    filter_horizontal = ['products_set']
    list_filter = ['borrower', 'created_date', 'status']

您也可以使用**filter_vertical**属性[Django-doc],其中两个框显示在彼此的上下。

相关问题