Django 不同ContentType的CharField选项
假设我有这个模型:Django 不同ContentType的CharField选项,django,database,python-3.x,django-models,Django,Database,Python 3.x,Django Models,假设我有这个模型: class TaggedItem(models.Model): tag = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'o
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
sub_type = models.CharField(choices=CHOICES)
及
是否有办法根据所涉及的内容类型排除某些选项?覆盖保存方法可能是最好的方法(其他信号),请参阅相关文档。 尝试以下方法:
def save(self, *args, **kwargs):
if self.content_type: # your logic
self.CHOICES = restricted_choices
super().save(*args, **kwargs)
根据您需要如何限制这些选择,有几种方法。是通过表单还是其他方式?@事实上,我希望在插入之前在数据库级别执行此操作。您可以使用django的
pre\u save
信号来检查实例内容,或者覆盖模型的保存方法,并插入您的逻辑以限制self.CHOICES
。谢谢,这正是我想要的!如果你这样做,我会接受这个答案。
def save(self, *args, **kwargs):
if self.content_type: # your logic
self.CHOICES = restricted_choices
super().save(*args, **kwargs)