gpt4 book ai didi

django - 跨表序列化 Django REST Framework

转载 作者:行者123 更新时间:2023-12-02 00:59:52 25 4
gpt4 key购买 nike

我有两个具有多对多关系的模型,我正在尝试使用 Django REST Framework 返回一些 geojson。我要返回的数据是 pub_date 和坐标(由 GeoDjango 中的 PointField 表示)。每次我尝试返回 geojson 时,我都会收到错误消息 Field name 'city' is not valid for model 'Article'。我是 django/geodjango 的新手,这是我第一次使用 Django REST Framework。我已经阅读了文档,但无法弄清楚我哪里出错了(或者甚至可能从哪里开始)。

这是我的模型和序列化程序。

模型.py:

class Location(models.Model):
city = models.CharField(max_length=200)
country = models.CharField(max_length=200)
continent = models.CharField(max_length=200)
point = models.PointField(srid=4326)
objects = models.GeoManager()

def __unicode__(self):
return u'%s' % (self.point)

class Meta:
db_table = 'location'

class Article(models.Model):
authors = models.ManyToManyField(Author)
locations = models.ManyToManyField(Location, related_name='places')
article_title = models.CharField(max_length=200, unique_for_date="pub_date")
pub_date = models.DateTimeField('date published')
article_keywords = ArrayField(ArrayField(models.CharField(max_length=20, blank=True), size=10), size=10,)
title_id = models.CharField(max_length=200)
section_id = models.CharField(max_length=200)

def __unicode__(self):
return u'%s %s %s' % (self.article_title, self.pub_date, self.article_keywords)

class Meta:
db_table = 'article'

序列化器.py

class ArticleSerializer(serializers.ModelSerializer):
places = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = Article
fields = ('places')

我想要的输出:

{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"time": "2013-01-22 08:42:26+01"
},
"geometry": {
"type": "Point",
"coordinates": [
7.582512743,
51.933292258,
1
]
}
},
{
"type": "Feature",
"properties": {
"time": "2013-01-22 10:00:26+01"
},
"geometry": {
"type": "Point",
"coordinates": [
7.602516645,
51.94962073,
1
]
}
}

提前致谢!

更新!我设法通过嵌入在查询集中的原始 SQL 查询找到了某个地方,但这不太正确:

serialize('geojson', Article.objects.raw('
select a.id, a.pub_date, al.location_id, l.point
from article a
join article_locations al on a.id = al.article_id
join location l on al.location_id = l.id'),
geometry_field = 'point',
fields=('pub_date','locations',))

结果是这样的:

{  
"type":"FeatureCollection",
"crs":{
"type":"name",
"properties":{
"name":"EPSG:4326"
}
},
"features":[
{
"geometry":null,
"type":"Feature",
"properties":{
"pub_date":"2015-04-06T20:38:59Z",
"locations":[
3
]
}
}

最佳答案

DRF 序列化程序可以做两件事:

  1. 将复杂数据(例如查询集)序列化为原生 Python 数据类型

    serializer = CommentSerializer(comment)
    serializer.data
    # {'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}
  2. 反序列化原生 Python 数据类型的数据

    serializer = CommentSerializer(data=data)
    serializer.is_valid()
    # True
    serializer.validated_data
    # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}

在你的情况下

All I want is to return all article pub_dates and their corresponding article coordinates lat/long's (from the pointField).

你必须做两件事:

  1. 使用对象、对象的列表查询集创建复杂的数据结构。

    在您的情况下,这非常简单,您只需要一个包含所有文章和 prefetched 的查询集位置,以防止对每个 location 进行不必要的数据库命中。

    Article.objects.all().prefetch_related('locations')[:10]
  2. 创建一个可以序列化此查询集的序列化程序。

    因为你有嵌套的数据结构(一个article可以有很多locations)你最好把它分成两个独立的序列化器。

    第一个只知道如何序列化locations,第二个只知道如何序列化articles,但它将使用第一个article.locations 序列化。

    class LocationSerializer(serializers.ModelSerializer):
    class Meta:
    model = Location
    fields = ('point',)


    class ArticleSerializer(serializers.ModelSerializer):
    #this way we override the default serialization
    #behaviour for this field.
    locations = LocationSerializer(many=True)

    class Meta:
    model = Article
    fields = ('pub_date', 'locations')

最后,您可以通过 ViewSet 组合 12

class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
#read about pagination in order to split this into pages
queryset = Article.objects.all().prefetch_related('locations')[:10]

关于django - 跨表序列化 Django REST Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29902287/

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