在Django rest框架中显示外键链接模型

时间:2019-11-21 23:00:48

标签: python django django-rest-framework

我想在树状视图中显示三个模型

 Event Market
           Runner
           Runner
           Runner
      Market
           Runner
           Runner  

事件可以有多个市场,市场可以有多个参与者。 我希望能够从一个api请求中获取这些模型,以便在必要时查看和删除旧事件。

我尝试创建组合的序列化器,但是出现一条错误消息,指出URL名称对Runner无效。我认为在组合的序列化程序中引用Runner模型是不正确的,因为Runner网址已更改为与组合相同的名称。

{
    "events": "http://localhost:8000/api/events/",
    "markets": "http://localhost:8000/api/markets/",
    "runners": "http://localhost:8000/api/combined/",
    "balance": "http://localhost:8000/api/balance/",
    "combined": "http://localhost:8000/api/combined/"
}

最好的方法是什么?

class Event(models.Model):
    sport_id = models.CharField(max_length=15)
    event_id = models.BigIntegerField(unique=True)
    event_name = models.CharField(max_length=200)
    start_time = models.DateTimeField(null=True)
    status = models.CharField(max_length=13)


class Market(models.Model):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    market_id = models.BigIntegerField(unique=True)
    market_name = models.CharField(max_length=35)
    status = models.CharField(max_length=10)
    volume = models.FloatField(null=True)

class Runner(models.Model):
    event = models.ForeignKey(Event, null=True, default=None, on_delete=models.CASCADE)
    market = models.ForeignKey(Market, null=True, default=None, on_delete=models.CASCADE)

    runner_id = models.BigIntegerField(unique=True)
    name = models.CharField(max_length=500)
    back_odds = models.FloatField(null=True)
    lay_odds = models.FloatField(null=True)


class CombinedSerializer(serializers.ModelSerializer):
    event = EventSerializer()
    market = MarketSerializer()

    class Meta:
        model = Runner
        fields = ('id','runner_name','runner_id', 'name', 'event' ,'market')


class CombinedViewSet(mixins.ListModelMixin, 
                     viewsets.GenericViewSet, 
                     mixins.RetrieveModelMixin):

   queryset = Runner.objects.all()
   serializer_class = CombinedSerializer   

1 个答案:

答案 0 :(得分:0)

从您的模型中,您对事件和市场中的跑步者都具有双重依赖性,这两者都是null = True,下面的代码用来构建喜欢的树

seqinfo=$(paste <(echo "$var1") <(echo "$var2"))

序列化器

command substitution: line 13: syntax error near unexpected token `('
command substitution: line 13: `paste <(echo "$var1") <(echo "$var2"))'
在事件类(内部类)末尾添加

模型

event:[
    runners:[
      runnner1 (not market dependable)
      ...
      runnnerx (not market dependable)
      ]
    markets:[
        maket1:[
            runner1
            ...
            runnery
        ],
       market2:[
           ...]

视图-具有GET(列表)选项的简单视图

很抱歉输入错误或简单的缺点-在这里输入