如何 'order_by' 在 Django 中使用一个字段建立几个层次关系的模型对象

How to 'order_by' model objects in Django using a field several levels of relationship apart

我有一个应用程序的多个模型,其中包含为不同公司生成表单的选项。我正在使用 mySQL。另外,我是菜鸟:(

FSForm 是主窗体。每当生成它时,它都会从 'Company' 对象中获取其 'fskey'(某些逻辑确定 select 的两个键中的哪一个)。

一个表单可以有很多 'FSRows'。 Django 确定哪些行 select 并填充 'FSForm' 如下。

检索到属于表单 'fskey' 的 'FSKeyRow' 个对象。然后,这些对象中相应的 'FSRows' 被填充为该表单的 'FSDataPoint' 模型的对象。

以下是我的模型:

class Company(models.Model):
    """Represents all companies"""
    symbol = models.CharField(max_length=5)
    name = models.CharField(max_length=255)
    annual_fskey = models.ForeignKey("FSKey", on_delete=models.CASCADE, related_name="company_annual_key")
    qtr_fskey = models.ForeignKey("FSKey", on_delete=models.CASCADE, related_name="company_qtr_key")

class FSForm(models.Model):
    """Represents all forms"""
    company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="company_fsform")
    functional_currency = models.ForeignKey("Currency", on_delete=models.CASCADE, related_name="fsform_currency")
    fskey = models.ForeignKey("FSKey", on_delete=models.CASCADE, related_name="fsform_key")

class FSKey(models.Model):
    """Represents keys which determine the rows to populate in the FSForm"""
    name = models.CharField(max_length=100)
    comments = models.TextField(max_length=500, blank=True)
    create_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)

class FSRow(models.Model):
    """Represents all possible rows"""
    name = models.CharField(max_length=255)
    comments = models.TextField(max_length=500, blank=True)

class FSKeyRow(models.Model):
    """Represents all rows that pertain to a key. This tells Django which rows to populate for an FSKey"""
    key = models.ForeignKey("FSKey", on_delete=models.CASCADE, related_name="fskey_key")
    row = models.ForeignKey("FSRow", on_delete=models.CASCADE, related_name="fskey_row")
    ordering = models.IntegerField(default=0)

class FSDataPoint(models.Model):
    """Represents DataPoints of the form. These are generated when a form is created based on FSKey applied to that form."""
    form = models.ForeignKey("FSForm", on_delete=models.CASCADE, related_name="fsform_datapoint")
    row = models.ForeignKey("FSRow", on_delete=models.CASCADE, related_name="fsrow_datapoint")
    float_data = models.FloatField(null=True, blank=True)
    str_data = models.CharField(max_length=255, blank=True)

这些模型中的字段更多。我刚刚包括了我认为有必要的那些。

我需要检索 FSKeyRow 模型中 'ORDERING' 字段顺序中的表单的 'FSDataPoints'。我不能在 FSDataPoints 模型或 FSRows 模型中保留 'ordering' 字段,因为这些值可能随时针对每个 FSKey 发生变化,这必须影响所有相应的 FSDataPoint 对象。

如何从 views.py 开始按顺序访问 FSDataPoints? shorter/simpler越多越好。

我想这应该可以解决问题:

FSDataPoint.objects.order_by('row__fskey_row__ordering').all()