I need to connect a react native picker select element to another. I mean I have two models name Brand and Model. When I select Brand, the Model picker should fill with models which are belongs to this brand. I tried something like below, but I get "undefined is not a function (near '...models.map...')" error. How should I connect two pickers like this? Or where is my mistake?
class Brand(models.Model):
brand_name = models.CharField(max_length=20, blank = True, default = '')
class Model(models.Model):
brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
model_name = models.CharField(max_length = 20, blank = True, default = '')
class BrandViewSet(viewsets.ModelViewSet):
serializer_class = BrandSerializer
queryset = Brand.objects.all()
permission_classes = (AllowAny,)
@action(detail=True, methods=['GET'])
def getbrandmodels(self, request, pk=None):
brand = Brand.objects.get(id=pk)
models = Model.objects.filter(brand=brand)
serializer = ModelSerializer(data=models)
serializer.is_valid()
return Response(serializer.data)
const [brands, setBrands] = useState([]);
const [models, setModels] = useState([]);
const [brand, setBrand] = useState(1);
const [model, setModel] = useState(1);
useEffect(() => {
getBrands();
getmodels();
}, []);
const getBrands = () => {
fetch('http://127.0.0.1:8000/api/brands/', {
method: 'GET',
headers: {
}
})
.then( res => res.json())
.then( jsonRes => setBrands(jsonRes))
.catch( error => console.log(error));
}
const getmodels = (value) => {
setBrand(value);
fetch(`http://127.0.0.1:8000/api/brands/${brand}/getbrandmodels`, {
method: 'GET',
headers: {
}
})
.then( res => res.json())
.then( jsonRes => setModels(jsonRes))
.catch( error => console.log(error));
}
return (
<View style={styles.container}>
<RNPickerSelect style={StyleSheet.flatten(styles.picker)} itemStyle={styles.pickerItem}
useNativeAndroidPickerStyle={false}
selectedValue={brand}
onValueChange={value=>getmodels(value)}
doneText = 'Tamam'
items={brands.map(obj => (
{
key: obj.id,
label: obj.brand_name,
value: obj.id,
color: "rgba(77,38,22,1)",
}))}
>
</RNPickerSelect>
<RNPickerSelect style={StyleSheet.flatten(styles.picker)} itemStyle={styles.pickerItem}
useNativeAndroidPickerStyle={false}
selectedValue={model}
onValueChange={value=>setModel(value)}
doneText = 'Tamam'
items={models.map(obj => (
{
key: obj.id,
label: obj.model_name,
value: obj.id,
color: "rgba(77,38,22,1)",
}))}
>
</RNPickerSelect>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'orange',
padding: 5
},
label: {
fontSize: 15,
color: 'white',
padding: 10
},
input: {
fontSize: 20,
backgroundColor: '#fff',
padding: 5,
margin: 5
},
picker: {
// flex: 1,
width: "100%",
height: 44,
},
pickerItem: {
height: 44
}
});
I do not know why but again I solved it after ask here :)
I only changed my getbrandmodels method in viewset as below.