django 自动列出多对多模型中的字段

mitkmikd  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(148)

我创建了一个分析类型模型,然后创建了一个表,将多个分析分组到一个组中:

class AnalysisType(models.Model):
    a_name = models.CharField(max_length=16,primary_key=True)
    a_measur = models.CharField(max_length=16)
    a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)
    # analysis_group = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1)
    def __str__(self):
        return f"{self.a_name} - {self.a_measur}"

class AnalysysGroup(models.Model):
    group_name = models.CharField(max_length=32)
    analysis = models.ManyToManyField(AnalysisType, blank=True)
    def __str__(self):
        return f"{self.group_name}"

我想通过管理面板选择乘加值(即,我选择了分析类型,然后在下面显示要填写的字段)

class PatientGroupAnalysis(models.Model):
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    analysis_date = models.DateTimeField()
    analysis_type = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1)
    # amalysis_data = ???
    def __str__(self):
        return f"{self.patient}:  {self.analysis_date} - {self.analysis_type} - {self.analysis_data}"

我尝试使用analysis_data = analysis.type.objects.all()等,但这是错误的方式。

yzuktlbb

yzuktlbb1#

试试这个:

具有StackedInline的管理面板

from django.contrib import admin
from .models import AnalysisType, PatientGroupAnalysis

# Register your models here.

class PatientGroupAnalysisInline(admin.StackedInline):
    model = PatientGroupAnalysis

@admin.register(AnalysisType)
class AnalysisTypeAdmin(admin.ModelAdmin):
    list_display = ["id", "a_name", "a_measur", "a_ref_min", "a_ref_max"]
    search_fields = ("id", "a_name")
    inlines = [PatientGroupAnalysisInline]

相关问题