0

在查询集中,我想返回一个集合(通过 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"
              }
         ]
    }
]
}
4

1 回答 1

1

您必须自己构建数据结构。您想要的基本上是两个查询,而您无法一次调用。

data = {"collection":None, "sales":[]}
for coll in Collection.objects.filter(sales__status="ACTIVE"):
   data["collection"] = coll
   for collsales in coll.collectionsales_set.filter(status="ACTIVE")
      data["sales"].append(collsales.collection)
于 2013-03-26T16:10:03.573 回答