如何解决添加基于所选文件的 m2m 文件使用
我正在尝试将国家/地区“拉丁美洲”或“欧洲”转换为国家/地区列表并将其保留为一个国家/地区。
例如,当您在国家/地区列表中选择 Latam 时,该 m2m 的结果必须是:[拉丁美洲、阿根廷、智利、秘鲁等]
数据库就是这样构建的...我知道最好将其拆分为区域和国家,但我现在无法更改它。
这是我做的方法。我认为这不是解决问题的方法,但也许可以帮助您帮助我。
LATAM = [1,4,24]
class PromoManagement(models.Model):
[...]
house_id = models.CharField(max_length=6)
original_title = models.CharField(max_length=150,blank=True,null=True)
country = models.ManyToManyField(Country)
[...]
def save(self,*args,**kwargs):
self.original_title = get_orignal_title(self.house_id)
super().save(*args,**kwargs)
def region_check(sender,instance,action,**kwargs):
if action == 'post_add' or action == 'post_remove':
for country in instance.country.all():
if country.name == 'Latam':
for id in LATAM:
instance.country.add(code)
m2m_changed.connect(region_check,sender=PromoManagement.country.through)
已编辑:可能的解决方案
我设法让它像这样工作:
def latam_region_converter(sender,pk_set,**kwargs):
if action == 'post_add' and 95 in pk_set:
# Latam id is 95
instance.country.add(2,62,6,3,45,103,36,42,104,43,34,44,7,46,37,75,35,58,38)
问题在于,如果用户手动删除该国家/地区之一,则应删除 latam。
if action == 'post_remove':
# Then it checks if the country removed is on the list of latam. If true it deletes the id 95 from the list.
解决方法
这是我解决的方法。
LATAM = (2,62,6,3,4,45,103,36,42,104,43,34,44,7,46,37,75,35,58,38)
def latam_region_converter(sender,instance,action,pk_set,**kwargs):
if action == 'post_add' and 95 in pk_set:
# Latam id is 95
print('Adding latam countries')
instance.country.add(2,38)
if action == 'post_remove' and any(item in LATAM for item in pk_set):
print('Removing Latam')
instance.country.remove(95)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。