我正在使用四个表:
class Product(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=40, unique=True)
acronym = models.CharField(max_length=3, unique=True)
class Alarm(models.Model):
active = models.BooleanField(default=True)
product = models.ForeignKey(Product) #NEW
name = models.CharField(unique=True, max_length=35)
image_file = models.CharField(max_length=30)
class File(models.Model):
reference = models.CharField(max_length=40)
product = models.ForeignKey(Product, related_name='item_product') #NEW
created = models.DateTimeField(default=datetime.now)
created_by = models.ForeignKey(User)
class FileAlarm(models.Model):
file = models.ForeignKey(File)
created = models.DateTimeField()
created_by = models.ForeignKey(User, related_name="alarm_created_by")
alarm_date = models.DateField(default=datetime.now)
alarm_type = models.ForeignKey(Alarm)
alarm_comment = models.CharField(max_length=80, blank=True, null=True)
不幸的是,我需要将onChange
事件传递给FileAlarm.alarm_type
的表单元素(这意味着queryset
中的__init__
无效)所以我需要填充{ {1}}变量choices=
。我只是想知道如何做到这一点,因为我只想要ChoiceField
的警报并且链接到与active
链接的product
相同的File
。 / p>
FileAlarm
答案 0 :(得分:0)
事实证明最好的方法是:
class FileAlarmForm(ModelForm):
def __init__(self,file,*args,**kwargs):
super(FileAlarmForm, self).__init__(*args, **kwargs)
p = Product.objects.get(id=file.product_id)
self.fields['alarm_type'].widget = Select(attrs={'onchange':'updateAlarmImage'})
self.fields['alarm_type'].queryset = Alarm.objects.filter(product=p)