'PUT request on list with foreign key fields issue
I need help figuring out how to update a list that has two foreign key fields that are the primary keys from two different tables. The below function allows for update or create if all fields in the request data list is of the same model (and is of no issue in tables that only have fields from its own model), but I get aCannot assign "'FND1'": "Table_C.Table_A_pk" must be a "Table_A" instance when trying to update this table that has those two foreign keys.
The goal is to be able to send a list update to Table_C and have the relevant Table_A and Table_B fields to be updated on any changes in the json sent.
Models:
class TableA(models.Model):
Table_A_pk = models.CharField(primary_key=True)
class TableB(models.Model):
Table_B_pk = models.CharField(primary_key=True)
class TableC(models.Model):
Table_C_pk = models.AutoField(primary_key=True)
Table_A_pk = models.ForeignKey(Table_A, on_delete=models.CASCADE)
Table_B_pk = models.ForeignKey(Table_B,
on_delete=models.CASCADE)
class Meta:
unique_together = ('Table_A_pk', 'Table_B_pk')
Table C represents the table I want to update, Table A and B are the tables that are parent tables to Table C.
Table A (imagine this is one dict in table A)
{
"Table_A_pk": "1",
}
Table B (imagine this is one dict in table B)
{
"Table_B_pk": "A",
}
Table C (update json in a list, how can I PUT this and update the foreign keys?)
[
{
"Table_C_pk": 1,
"Table_A_pk: "3", (foreign key from Table A)
"Table_B_pk: "B" (foreign key from Table B)
}
]
I've tried breaking up the instance object and trying to assign the field within by directly referencing Table A and B's PK by getting objects from their model, but that isn't working so far either.
Put method in Table_C modelviewset. It works just fine for other viewsets that only have fields from their own instance, but in this case, it gives a 'Cannot assign "'3'": "Table_C.Table_A_pk" must be a "Table_A" instance.'
@transaction.atomic
def put(self, request):
objects = list(request.data)
for o in objects:
try:
instance = self.model.objects.get(
**{self.lookup_field: o.get(self.lookup_field)}
)
except self.model.DoesNotExist:
instance = self.model(**o)
instance.save(update_fields=['PercentOfFundNetAssets'])
return Response(objects, status=status.HTTP_200_OK)
Any ideas?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
