我使用Django Framework
+ Django REST Framework
+ Angular 4
。
我有通过contenttype
实现的多态链接。
API附带以下数据:
/ api / v1 / products /
{
"id": 3,
"treaty_number": "asda",
"days_left": null,
"days_left_before_the_next_payment": null,
"contact": "",
"additional_information": "",
"no_prolongation": false,
"improving_conditions": "",
"redundancy": null,
"is_general": false,
"insurant": {
"id": 1,
"object_id": 1,
"content_type": 35 <--- HERE MODEL ID (artifical_persons)
},
"insurer": null,
"executor": null,
"status": null,
"dates": null,
"subagent": null,
"broker": null
},
我需要通过content_type_id和object_id确定相应的条目,并在mat-select中输出其名称:
<mat-form-field>
<mat-select placeholder="Insurants">
<mat-option *ngFor="let insurant of insurants [value]="insurant.value">
{{insurant.name}}
</mat-option>
</mat-select>
</mat-form-field>
/ api / v1 / artifical_persons /
[
{
"id": 1, <--- HERE OBJECT_ID
"name": "Test",
"id_holdings": null
}
]
我将不胜感激。我的想法是我需要编写一个函数,该函数将通过HTTP接受两个参数(content_type_id,object_id)并返回保险人名称。
model.py
class Insurants(models.Model):
id = models.AutoField(primary_key=True)
# insurant_id = models.CharField(max_length=512)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Products(models.Model):
id = models.AutoField(primary_key=True)
treaty_number = models.CharField(max_length=512)
....
insurant = models.ForeignKey(Insurants, null=True, blank=True)
....
class Meta:
db_table = 'products'
def __str__(self):
return '{} '.format(self.treaty_number)
serializers.py
class InsurantsSerializer(serializers.ModelSerializer):
class Meta:
model = Insurants
depth = 1
fields = (
'id',
'content_type',
'object_id',
)
class ProductsNewSerializer(QueryFieldsMixin, serializers.ModelSerializer):
class Meta:
model = Products
depth = 1
fields = (
'id',
'treaty_number',
...
'insurant',
...
)