微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过多级反向查找获取对象

如何解决如何通过多级反向查找获取对象

在我的项目中,共有三种模型:

class Level1(models.Model):
        name = models.CharField(max_length=250)


class Level2(models.Model):
        name = models.CharField(max_length=250)
        level1 = models.ForeignKey(Level1,on_delete=models.RESTRICT)

class Level3(models.Model):
        name = models.CharField(max_length=250)
        level2 = models.ForeignKey(Level2,on_delete=models.RESTRICT)

Level1 模型有 2 个对象 WATXLevel2 有 5 个对象 AAABBB,其中外键是 WA;和 AAA,CCC,DDD 其中外键是 TX

Level3中,我想添加一个对象RRRR,其中Level2的外键对象是AAA

当我尝试通过 Level2.objects.get(name='AAA') 获取 Level2 时,它显示错误 get() returned more than one Level2 -- it returned 2!

如何解决这个问题。提前致谢。

解决方法

是的,这是因为 get 方法只允许检索您可以使用的一个对象

 @Override
    public void onMapReady(@NonNull final MapboxMap mapboxMap) {

        try {
            mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/mapbox/cjf4m44iw0uza2spb3q0a7s41")

                    // Add the SymbolLayer icon image to the map style
                    .withImage(ICON_ID,BitmapFactory.decodeResource(
                            MainActivity.this.getResources(),R.drawable.mapbox_marker_icon_default))

                    // Adding a GeoJson source for the SymbolLayer icons.
                    .withSource(new GeoJsonSource("ports",new URI("https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson")))

                    // Adding the actual SymbolLayer to the map style. An offset is added that the bottom of the red
                    // marker icon gets fixed to the coordinate,rather than the middle of the icon being fixed to
                    // the coordinate point. This is offset is not always needed and is dependent on the image
                    // that you use for the SymbolLayer icon.
                    .withLayer(new SymbolLayer(LAYER_ID,SOURCE_ID)
                            .withProperties(
                                    iconImage(ICON_ID),iconAllowOverlap(true),iconIgnorePlacement(true)
                            )
                    ),new Style.OnStyleLoaded() {
                @Override
                public void onStyleLoaded(@NonNull Style style) {

                    // Map is set up and the style has loaded. Now you can add additional data or make other map adjustments.


                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
,

get 期望只找到一个对象,否则会出错。您可以添加更多查找

Level2.objects.filter(name='AAA',level1__name='WA') or 
Level2.objects.filter(name='AAA',level1__name='TX')
,

Alhamdulillah,最后我通过结合 filterget 解决了这个问题。

Level2.objects.filter(level1__name='WA').get(name='AAA')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。