问题描述
在我的项目中,共有三种模型:
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 个对象 WA
,TX
。 Level2 有 5 个对象 AAA
,BBB
,其中外键是 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,最后我通过结合 filter 和 get 解决了这个问题。
Level2.objects.filter(level1__name='WA').get(name='AAA')