Contenttype Django + Angular 4 - PullRequest
       20

Contenttype Django + Angular 4

0 голосов
/ 08 января 2019


Я использую 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>

/ апи / v1 / artifical_persons /

[
    {
        "id": 1, <--- HERE OBJECT_ID
        "name": "Test",
        "id_holdings": null
    }
]

Буду признателен за любую помощь. Я думаю, что мне нужно написать функцию, которая будет принимать два аргумента (content_type_id, object_id) через HTTP и возвращать имя страхователя.

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',
            ...
        )
...