问题
I'am creating a django application with a database including the following tables:
I created the models as following:
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'
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?
回答1:
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
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
.
Some additional notes
Class names should be singular
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.
- It's group and not group_id, We all know that in SQL it's the group_id, however, This is python and you have access to the whole group instance then you
instance.id
orinstance.pk
to get it.
来源:https://stackoverflow.com/questions/61481929/django-one-to-many-get-all-underlying-records