You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js结合Django REST Framework无法获取外键关联对象字段

问题根源

Django Rest Framework 自带的ModelSerializer对外键字段的默认处理逻辑是仅返回关联对象的主键ID,不会自动序列化外键对象的其他字段。你当前接口返回的每条商品数据里,store字段只是一个数字ID,不是完整的店铺对象,所以前端无法读取store.name、store.slug属性。

修复方案

1. 重写序列化器,嵌套返回需要的店铺字段

先定义一个精简版的店铺序列化器,只返回前端需要的字段,再在商品序列化器里覆盖默认的store外键字段:

# serializer.py
from rest_framework import serializers
from .models import Product, Store

class StoreLiteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Store
        fields = ['id', 'name', 'slug'] # 按需返回字段,不要冗余数据

class ProductSerializer(serializers.ModelSerializer):
    store = StoreLiteSerializer(read_only=True) # 覆盖默认外键字段,返回嵌套店铺对象
    class Meta:
        model = Product
        fields = '__all__'

2. 优化视图查询集,避免N+1查询问题

关联查询时加上select_related提前连表查询,大幅减少数据库查询次数,提升接口性能:

# views.py
class ProductListAPIView(generics.ListAPIView):
    pagination_class = MyCustomPagination
    queryset = Product.objects.select_related('store', 'category', 'sub_category', 'created_by').order_by('-date_created')
    serializer_class = ProductSerializer

3. 修正Vue模板的属性绑定语法

你原来的href绑定写法有误,v-bind绑定的属性值内部直接写JS表达式即可,不需要嵌套插值标记:

<!-- 错误写法 -->
<a class="text-dark text-decoration-none" v-bind:href="[[ product.store.slug ]]+'products/'+[[ product.slug ]]">

<!-- 正确写法 -->
<a class="text-dark text-decoration-none" v-bind:href="`${product.store.slug}/products/${product.slug}`">

额外注意

你的Product模型里store字段设置了null=True,可能存在没有关联店铺的商品,建议模板里加一层判空,避免前端取值报错:

<div v-else v-for="product in products" class="col">
  <a v-if="product.store" class="text-dark text-decoration-none" v-bind:href="`${product.store.slug}/products/${product.slug}`">
    <div class="card border-0">
      <!-- 其他商品内容 -->
      <h1 v-if="product.store">[[ product.store.name ]]</h1>
      <!-- 其他商品内容 -->
    </div>
  </a>
</div>

改完重启Django服务,再访问接口就能看到每条商品数据里包含嵌套的store对象,前端可以正常读取对应字段渲染。

内容的提问来源于stack exchange,提问作者Arthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 03:03:39