无法获取 Django 休息框架数据表外键数据

Django rest framework datatables foreign key data could not be obtained

我的问题是,当我向我的 table 添加外键时,我遇到了一些问题,例如无法获取价值和无法过滤下面的 table 我共享模型和序列化程序。

class Foo(models.Model):
    name = models.CharField(max_length=77, unique=True)
    phone = models.CharField(max_length=40, null=True, blank=True)
    email = models.CharField(max_length=80, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name}"

class Process(models.Model):
    foo = models.ForeignKey(Foo, on_delete=models.CASCADE)

class ProcessSerializer(serializers.ModelSerializer):
    class Meta:
        model = Process
        fields = '__all__'

<th data-data="foo.name" data-name="foo.name">Foo</th>

我正在向我的模型添加一个外键然后使用 djangorestframework-datatables 包我无法获得名称属性我只是为外键获得一个像“1”这样的 id,并且在添加 .数据数据中 foo 模型的名称我无法获得任何值。我收到以下错误

DataTables warning: table id=processes - Requested unknown parameter 'foo.name' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4

我在代码中没有发现任何问题,欢迎任何帮助。

Table 属性:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Processes</title>
  <meta name="description" content="Processes">
  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css">
  <link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/dataTables.bootstrap4.min.css">
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-sm-12">
        <table id="processes" class="table table-striped table-bordered" style="width:100%" data-server-side="true" data-ajax="/api/processes/?format=datatables">
          <thead>
            <tr>
              <th data-data="foo.name" data-name="foo.name">Foo</th>
              <th data-data="process">Process</th>
            </tr>
          </thead>
        </table>
      </div>
    </div>
  </div>
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
  <script src="//cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
  <script>
      $(document).ready(function() {
          $('#processes').DataTable();
      });
  </script>
</body>
</html>

我猜你要找的是Nested Relationships

您需要添加 FooSerializer class 并更新您的 ProcessSerializer


...

# Include this class
class FooSerializer(serializers.ModelSerializer):

    class Meta:
        model = Foo
        fields = '__all__'

class ProcessSerializer(serializers.ModelSerializer):
    foo = FooSerializer(read_only=True) # serialize the Foo Object

    class Meta:
        model = Process
        fields = '__all__'