1

我有以下型号

# filename - stocks.models
class Stock(models.Model):

    ticker = models.CharField(max_length=10, unique=True, primary_key=True)
    exchange = models.CharField(default="", max_length=10)
    name = models.CharField(default="", max_length=255)
    slug = models.SlugField(default="", editable=False)

    def save(self, *args, **kwargs):
        value = self.ticker
        self.slug = slugify(value, allow_unicode=True)
        super().save(*args, **kwargs)

    class Meta:
        verbose_name = "stock"
        verbose_name_plural = "stocks"
        ordering = ["ticker"]

# filename - prices.models

from viewflow.fields import CompositeKey


class StockPrice(models.Model):
    id = CompositeKey(columns=["ticker_id", "date"])
    ticker = models.ForeignKey(
        "stocks.Stock", on_delete=models.CASCADE, related_name="stocks"
    )
    date = models.DateTimeField(default=now)
    open = models.FloatField()
    high = models.FloatField()
    low = models.FloatField()
    close = models.FloatField()
    adj_close = models.FloatField()
    volume = models.FloatField()

以下意见

class StockViewSet(viewsets.ModelViewSet):
    queryset = Stock.objects.all()
    queryset = queryset.prefetch_related("stocks")
    serializer_class = StockSerializer
    lookup_url_kwarg = "ticker"
    lookup_field = "ticker__iexact"

    # override create method to include many=True
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(
            data=request.data, many=isinstance(request.data, list)
        )
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(
            serializer.data, status=status.HTTP_201_CREATED, headers=headers
        )

#filename prices.views
class StockPriceViewSet(viewsets.ModelViewSet):
    queryset = StockPrice.objects.all()
    serializer_class = StockPriceSerializer

和以下路由器

router = routers.SimpleRouter()
router.register(r"stocks", stock_views.StockViewSet, basename="stocks")

stockprice_router = routers.NestedSimpleRouter(router, r"stocks", lookup="stocks")
stockprice_router.register(r"price", price_views.StockPriceViewSet)

urlpatterns = [
    path("", include(router.urls)),
    path("", include(stockprice_router))
]

路由器来自drf-nested-routers. 我如何设置一个 url,例如localhost:8000/stocks/appl/price/将显示models.StockPrice特定股票 aapl 的反向外键数据 ()。

目前,当我访问时,localhost:8000/stocks/appl/price我可以同时查看所有股票价格。

4

1 回答 1

1

get_queryset在这种情况下,根据选定的股票代码,覆盖以过滤掉嵌套视图集将处理的对象,因此:

class StockPriceViewSet(viewsets.ModelViewSet):
    queryset = StockPrice.objects.all()
    serializer_class = StockPriceSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        ticker = self.kwargs.get('stocks_ticker')
        if ticker:
            queryset = queryset.filter(ticker__ticker=ticker)
        return queryset

以上是如果StockPriceViewSet可以用作非嵌套视图集。但 ifStockPriceViewSet仅嵌套在StockViewSet

class StockPriceViewSet(viewsets.ModelViewSet):
    serializer_class = StockPriceSerializer
    def get_queryset(self):
        return StockPrice.objects.filter(ticker__ticker=self.kwargs['stocks_ticker'])
于 2021-09-01T00:36:58.147 回答