在查询集中,我想返回一个集合(通过 pk)和所有具有 status='ACTIVE' 的 Sales 对象。
我努力了:
Collection.objects.filter(Sales__status="ACTIVE")
但是,如果其中一个 Sales 对象与条件匹配,而不仅仅是状态为“ACTIVE”的对象,我将取回包含所有 Sales 对象的集合对象
所以我有 2 个模型(和一个参考模型)
class Collection(models.Model):
ID = models.AutoField(primary_key=True)
collection_title = models.CharField(max_length=255)
class Sales(models.Model):
ID = models.AutoField(primary_key=True)
sales_title = models.CharField(max_length=255)
class CollectionSales(models.Model):
COLLECTIONSALES_STATUS_LIST = (
('ACTIVE', 'Active'),
('REJECT', 'Reject'),
)
collection = models.ForeignKey('Collection')
sales = models.ForeignKey('Sales')
status = models.CharField(max_length=10, choices=COLLECTIONSALES_STATUS_LIST, default="ACTIVE")
class Meta:
db_table = "myschema_collection_sales"
managed=False
编辑:我正在尝试将其放入 Rest-Framework 以便输出为:
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"ID": "1",
"collection_title": "My Collection 1",
"Sales": [
{
"ID": 12,
"sales_title": "my sales title 12",
"status": "ACTIVE"
}
]
}
,
{
"ID": "2",
"collection_title": "My Collection 2",
"Sales": [
{
"ID": 4,
"sales_title": "my sales title 4",
"status": "ACTIVE"
},
{
"ID": 5,
"sales_title": "my sales title 5",
"status": "ACTIVE"
}
]
}
]
}