Serializer字段命名不正确

时间:2018-03-06 21:42:07

标签: python django django-views

我正在尝试提供一些序列化数据,并在尝试获取字段name的值时收到AttributeError。

models.py:

class Resource(models.Model):
    """Initial representation of a resource."""
    # ID from fixture resources, for internal dedupe
    internal_id = models.CharField(max_length=20, null=True, blank=True)
    name = models.CharField(max_length=200)
    description = models.TextField(null=True, blank=True)
    categories = models.ManyToManyField("Category")
    neighborhoods = models.ManyToManyField("Neighborhood")
    email_contact = models.EmailField(null=True, blank=True)
    pdf = models.ManyToManyField("PDF")
    phone = models.CharField(max_length=200, blank=True, null=True)
    website = models.URLField(max_length=200, blank=True, null=True)

    # address
    street_address = models.CharField(max_length=400, null=True, blank=True)
    city = models.CharField(max_length=100, null=True, blank=True)
    state = models.CharField(max_length=10, null=True, blank=True)
    latitude = models.FloatField(null=True, blank=True)
    longitude = models.FloatField(null=True, blank=True)
    zip_code = models.CharField(max_length=10, null=True, blank=True)

    # meta
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return u'{}'.format(self.name)

    @property
    def categories_str(self):
        return [str(t) for t in self.categories.all()]

    @property
    def neighborhoods_str(self):
        return [str(t) for t in self.neighborhoods.all() if t] or ["Houston"]

    @property
    def bookmark(self):
        """This is here to make it easier to serialize a standard resource."""
        return getattr(self, "_bookmark", None)

    @bookmark.setter
    def bookmark(self, bookmark):
        self._bookmark = bookmark

    def indexing(self):
        safe_zip = str(self.zip_code or "")
        safe_neighborhood = [n for n in self.neighborhoods.all() if n] or ["Houston"]
        obj = ResourceDoc(
            meta={"id": self.id},
            name=self.name,
            resource_suggest=self.name,
            email_contact=self.email_contact,
            phone=self.phone,
            description=self.description,
            website=self.website,
            categories=self.categories_str,
            street_address=self.street_address,
            city=self.city,
            state=self.state,
            zip_code=safe_zip,
            neighborhoods=self.neighborhoods_str,
            # TODO default to Houston for now but need a way to handle case where we don't know neighborhood or zip code
            location_suggest=[str(attr) for attr in chain([safe_zip], safe_neighborhood) if attr],
            created_at=self.created_at,
            modified_at=self.modified_at,
        )
        if self.latitude and self.longitude:
            obj.geo_coords = {
                "lat": str(self.latitude),
                "lon": str(self.longitude),
            }
        obj.save(index="welnity_production_2")
        return obj.to_dict(include_meta=True)

serializers.py:

class ResourceSerializer(serializers.ModelSerializer):
bookmark = BookmarkMetaSerializer(read_only=True)
notes = PrivateNoteSerializer(read_only=True, many=True)
categories = CategorySerializer(read_only=True, many=True)
neighborhoods = NeighborhoodSerializer(read_only=True, many=True)
class Meta:
    model = Resource
    fields = '__all__'

view.py:

class BookmarkGroupView(View):
    def get(self, request, *args, **kwargs):
        # resources = Resource.objects.filter(bookmarks__user=request.user)
        # resources = get_enriched_resources(request.user, resources)

        group = BookmarkGroup.objects.get(name='food')
        resources = group.bookmarks.all()
        serialized = ResourceSerializer(resources, many=True)
        context = {
            "component": "groups.js",
            "props": {
                "resources": JSONRenderer().render(serialized.data)
            }
        }
        return render(request, "groups.html", context)

错误是

Got AttributeError when attempting to get a value for field `name` on serializer `ResourceSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Bookmark` instance.
Original exception text was: 'Bookmark' object has no attribute 'name'.

任何帮助或方向将不胜感激!

1 个答案:

答案 0 :(得分:0)

您正在为ResourceSerializer提供错误的模型实例。

    resources = group.bookmarks.all()
    serialized = ResourceSerializer(resources, many=True)

此处,您告诉序列化工具使用group.bookmarks.all()作为数据源,这些数据源是Bookmark的实例,而不是Resource