问题描述
我有以下两种模型:
models.py
from django.db import models
from django.contrib.auth.models import User
class Skill(models.Model):
skill = models.CharField(max_length=50)
def __str__(self):
return self.skill
class Designer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
description = models.TextField(max_length=500, blank=True)
date_created = models.DateField(auto_now_add=True)
profile_img = models.ImageField(upload_to="gallery",null=True, blank=True)
skills = models.ManyToManyField(Skill, blank=True)
experience = models.IntegerField(blank=True, null=True)
account_type = models.CharField(max_length=10)
def __str__(self):
return self.user.username
Designer模型是User模型的扩展,它与Skill模型具有ManyToMany关系.我可以从管理页面向设计器实例添加技能,但是没有删除选项.如何获得管理页面上的删除选项?我还想在按钮单击上添加删除功能.如何在代码中添加它?
Designer model extends from User model and it has ManyToMany relationship with Skill model. I can add skills to designer instance from admin page but there is no delete option. How can I get the delete option on admin page? I also would like to add the delete functionality on button click. How can I add it in the code?
推荐答案
在 ManyToMany
关系字段中,没有 delete
功能,我们需要使用 remove
实例或为了清除字段值,我们需要使用 clear
链接
In ManyToMany
relationship field there is no delete
functionality we need to use remove
an instance for that or in order to clear the field value we need to use clear
link
为您辩护
our_desire_skill = skills.objects.filter(skill=search_skill)
desiner_user = Designer.objects.get(user=our_desire_user)
desiner_user.skills.remove(our_desire_skill)
如果要从管理页面更改 ManyToManyFields
,请确保该字段类似于 raw_id_fields
链接然后,您就可以更新您的 ManyToManyField
商店值从管理站点.
If you want to change ManyToManyFields
from admin page need to make sure that field is like raw_id_fields
link Then you can able to update your ManyToManyField
store value from admin site.
这篇关于从管理页面中删除Django中的ManyToManyField并单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!