Django一对多获取所有基础记录 [英] Django one to many get all underlying records

查看:49
本文介绍了Django一对多获取所有基础记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用包含以下表格的数据库创建django应用程序:

I'am creating a django application with a database including the following tables:

我创建了以下模型:

class Group(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
    text = models.CharField(db_column='Text', max_length=4000)

    class Meta:
        db_table = 'Group'


class Filters(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
    text = models.CharField(db_column='Text', max_length=4000)
    group_id = models.ForeignKey(Group, on_delete=models.CASCADE,
                                 db_column='GroupId')

    class Meta:
        db_table = 'Filters'

目标是调用一个端点并返回包含所有组和基础过滤器的列表.有可能实现这一目标吗?如果可能的话,我希望在Serializer类中使用它.

The goal is to call an endpoint and return a list with all Groups and underlying Filters. Is it possible to achieve this? If possible, I want it in a Serializer class.

我知道我可以获取过滤器记录的组,但是反过来这也是可能的吗?

I know I can get the group of a filter record, but is this also possible the otherway around?

推荐答案

class Group(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
    text = models.CharField(db_column='Text', max_length=4000)

    class Meta:
        db_table = 'Group'


class Filters(models.Model):
    id = models.AutoField(primary_key=True, editable=False)
    text = models.CharField(db_column='Text', max_length=4000)
    group = models.ForeignKey(Group, on_delete=models.CASCADE,
                                 db_column='GroupId', related_name='filters') # not group_id

这只是说,过滤器具有.group,而组具有.filters(相关名称),如果您未指定 related_name ,则默认为 model_qs ,因此应为 filters_qs .

This just says, Filters has .group but a group has .filters (related_name), If you didn't specify a related_name, It will be model_qs by default, so it should be filters_qs.

一些其他注释

  • 类名应为单数

Django通过添加's'创建复数名称,在您的情况下,它将创建过滤器,您将必须指定 verbose_name_plural (更多无用的代码)

Django creates plural names by adding 's', In your case it will create filterss and you'll have to specify a verbose_name_plural (more useless code)

除非您要重新创建已经存在的后端或需要该后端的东西,否则无需指定数据库数据,列名或其他任何内容.

You don't need to specify db data, column names or whatever unless you're re-creating a backend that already exists or something that needs that.

这篇关于Django一对多获取所有基础记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆