'How build a category model after building legacy model in Django REST Framework

Hello, I have a question about improving legacy models.

The Material model is old model, and i want to make category by using new model 'type'. But i have a little problem with when i use admin site. In admin site, i hope to choose the 'type' first, and upload data .. how can i make better

  • models
# new model 
class MaterialType(BaseModel):
    type = models.CharField(choices=MaterialTypeChoice.choices, max_length=50, null=True, blank=True)

    
    def __str__(self):
        return self.type

# old model
class Material(models.Model):
    type = models.ForeignKey(MaterialType, verbose_name=, null=True, blank=True, on_delete=models.SET_NULL)
    name = models.CharField max_length=50, null=True, blank=True)
    size = models.CharField(max_length=50, null=True, blank=True)
    unit = models.CharField(max_length=5, null=True, blank=True)
    price_unit = models.IntegerField(null=True, blank=True)

    
    def __str__(self):
        return self.name
  • serializers
# new
class MaterialTypeListSerializer(serializers.ModelSerializer):
    class Meta:
        model = MaterialType
        fields = ["type"]

# old
class MaterialListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Material
        fields = ["id", "type", "name", "size", "unit", "price_unit"]
  • views
# new
class MaterialTypeList(ListCreateAPIView):
    queryset = MaterialType.objects.all()
    serializer_class = MaterialTypeListSerializer

# old
class MaterialList(ListAPIView):
    queryset = Material.objects.all()
    filter_class = MaterialFilter
    serializer_class = MaterialListSerializer
  • admin
@admin.register(Material)
class MaterialAdmin(ImportExportModelAdmin):
    list_display = ["name", "size", "unit", "price_unit"]
    list_display_links = ("name",)
    list_filter = ("type",)
    list_per_page = 10
    # list_editable = ('type',)
    search_fields = ("name", "size")
    resource_class = MaterialResource

@admin.register(MaterialType)
class MaterialTypeAdmin(ImportExportModelAdmin):
    list_display = ["type"]

    list_filter = ("type",)
    list_per_page = 10
    # list_editable = ('type',)


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source