我正在尝试使用django来组织和管理我的临床研究数据。我想我只能使用管理界面,因为这是一个不需要公开的幕后数据库。我可以编程,但从来没有在python中,所以我陷入了简单的事情。
我有多次访问的患者。每次访问都涉及多次扫描。在管理界面中,我可以在每个患者页面上看到所有访问和所有扫描,作为内联。但是,在添加新扫描时,我该如何制作,以便选择与之相关联的访问仅限于相关患者的访问,而不是其他患者?
模型(简化):
class Patient(models.Model):
patient_id = models.CharField(max_length=16, primary_key=True)
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
class Visit(models.Model):
patient = models.ForeignKey(Patient)
visit_date = models.DateTimeField()
class Scan(models.Model):
patient = models.ForeignKey(Patient)
visit = models.ForeignKey(Visit)
scan_type = models.CharField(max_length=32)
非常感谢您的帮助......
答案 0 :(得分:1)
我认为 formfield_for_foreignkey 方法对您有所帮助。您可以在管理类中实现它。请参阅docs。
答案 1 :(得分:1)
两个例子略有不同:
首先:
class ScanInlineAdmin(admin.TabularAdmin):
model = Scan
formset = ScanInlineFormset
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "visit":
patient = self.get_object(kwargs['request'], Patient)
kwargs["queryset"] = Visit.objects.filter(patient=patient)
return super(ScanInlineAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
def get_object(self, request, model):
object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
try:
object_id = int(object_id)
except ValueError:
return None
return model.objects.get(pk=object_id)
第二
class ScanInline(admin.TabularInline):
model = Scan
formset = ScanInlineFormset
def formfield_for_dbfield(self, field, **kwargs):
if field.name == 'visit':
# Note - get_object hasn't been defined yet
patient = self.get_object(kwargs['request'], Patient)
vists = Visit.objects.filter(patient=patient)
return forms.ModelChoiceField(queryset=visits)
return super(ScanInline, self).formfield_for_dbfield(field, **kwargs)
def get_object(self, request, model):
object_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
try:
object_id = int(object_id)
except ValueError:
return None
return model.objects.get(pk=object_id)
您可能会发现此article有用。我假设您在患者页面管理员编辑/查看您要进入新扫描的位置。这是对的吗?