gpt4 book ai didi

python - Django Tastypie : Filtering by ForeignKey

转载 作者:行者123 更新时间:2023-12-01 04:43:27 24 4
gpt4 key购买 nike

我希望 Django Tastypie 返回由外键过滤的查询。这是我的两个模型:

class Origin(models.Model):
country = models.CharField(max_length=1024)

class Fruits(models.Model):
origin = models.ForeignKey(Origin)
fruit_name = models.CharField(max_length=1024)
is_sweet = models.BooleanField()
quantity = models.IntegerField()

基于文档here ,我正在使用以下资源.py:

class FruitResource(ModelResource):
class Meta:
queryset = Fruits.objects.all()
allowed_methods = ['get']
filtering = {
"origin": ('exact',)
}

这是我尝试访问的 URL:

http://localhost:8000/api/v1/fruit/?format=json&origin__country=Nepal

访问该 URL 将返回以下输出:

{
"meta":
{
"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 2}, "objects":
[
{"fruit_name": "Apple", "id": 1, "is_sweet": true, "quantity": 10, "resource_uri": "/api/v1/fruit/1/"},
{"fruit_name": "Banana", "id": 2, "is_sweet": true, "quantity": 10, "resource_uri": "/api/v1/fruit/2/"}
]
}

我应该提到的是,我使用此 URL 得到了相同的输出:

http://localhost:8000/api/v1/fruit/?format=json

通过指定 Origin 的国家/地区属性来获取 Fruits 对象列表的正确方法是什么?

最佳答案

我能够根据this answer让它工作。为了其他人的利益,我在这里列出了最终的代码。

from tastypie.resources import ModelResource, fields, ALL_WITH_RELATIONS

from fruits.models import Fruits
from origin.models import Origin

class OriginResource(ModelResource):
class Meta:
queryset = Origin.objects.all()
resource_name = 'origin'
filtering = {
"country": ('exact',)
}

class FruitResource(ModelResource):
origin = fields.ForeignKey(OriginResource, 'origin', full=True)
class Meta:
queryset = Fruits.objects.all()
allowed_methods = ['get']
filtering = {
"origin": ALL_WITH_RELATIONS,
}

使用此代码,如果我点击 http://localhost:8000/api/v1/fruit/?format=json&origin__country=Nepal ,我会得到以下预期输出:

{"meta": 
{"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1},
"objects": [{
"fruit_name": "Apple", "id": 1, "is_sweet": true, "origin":
{"country": "Nepal", "id": 3, "resource_uri": ""},
"quantity": 10, "resource_uri": "/api/v1/fruit/1/"
}]
}

关于python - Django Tastypie : Filtering by ForeignKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30021960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com