My Table structure is there are four tables
user
coin
exchange
their reference goes to
user_exchange_plan
with keys
user_id, coin_id, exchange_id
so i am creating a user exchange plan via api
for this i am sending a request like
{ "user": 1, "coin": 1, "exchange": 1, "plan_type": null, ..... }
but it is throwing validation error that all three are required. what could i be possibly doing wrong.
how can i save foreign keys in this record.
Following is the code for my serializer
`class UserTradePlanSerializer(serializers.ModelSerializer):
#code1
user = serializers.PrimaryKeyRelatedField(queryset=SUser.objects.all())
coin = serializers.PrimaryKeyRelatedField(queryset=Coin.objects.all())
exchange = serializers.PrimaryKeyRelatedField(queryset=Exchange.objects.all())
#code2
# user = SUserSerializer()
# coin = CoinSerializer()
# exchange = ExchangeSerializer()
def create(self, validated_data):
return UserTradePlan.objects.create(**validated_data)
class Meta:
model = UserTradePlan
fields = ("id", "user", "coin", "exchange", "plan_type", ....)
depth = 1`
if i activate the code written under #code1 then it will work as expected, but while retrieving it will not replace user with user object. it will return the id of that user plain.
if i activate the code written under #code2 and comment the code #code1 then while retrieving it replaces the user with object but it start throwing the validation error.
what is the appropriate way to save and retrieve the values of association table. So that when saved it saves the id and when retrieved it replaces it by object. i haven't used user_id field do i need to add it to send the value?
thanks
class User(models.Model):
...
class Coin(models.Model):
...
class Exchange(models.Model):
...
class UserExchangePlan(models.Model):
user = ForeignKey(User, ...)
coin = ForeignKey(Coin, ...)
exchange =ForeignKey(Exchange, ...)class UserExchangePlanSerializers(ModelSerializer):
class Meta:
model = UserExchangePlan
fields = '__all__'class UserExchangePlanViewSet(ModelViewSet):
queryset = UserExchangePlan.objects.all()
serializer = UserExchangePlanSerializersclass ListUserExchangePlan(ModelSerializer):
user = YourUserSerializer()
coin = YourCoinSerializer()
exchange = YourExchangeSerializer()
class Meta:
model = UserExchangePlan
fields = '__all__'