我正在 Django 中創建一個模型,但對我應該采用的欄位型別感到非常困惑:
問題:我必須在一個 Web 分類中訪問多個域,請告訴我如何建立這些欄位關系,以便如果我嘗試獲取一個 Web 分類詳細資訊,那么它也將包含相關域的串列。
模型.py:
class WebClassification(models.Model):
vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True)
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=1000)
domain_name = models.[what type i take here]
def __str__(self):
return self.name
域.py
class Domain(models.Model):
id = models.IntegerField()
domain_name = models.CharField(max_length=200)
def __str__(self):
return self.domain_name
uj5u.com熱心網友回復:
如果每個 Web 分類都應該包含相關域的串列,那么您應該在模型中包含一個ForeignKey欄位:DomainWebClassification
# models.py
class Domain(models.Model):
id = models.IntegerField()
web_classification = models.ForeignKey(WebClassification, on_delete=models.CASCADE)
domain_name = models.CharField(max_length=200)
def __str__(self):
return self.domain_name
您將為WebClassification模型創建一個序列化程式:
# serializers.py
from rest_framework import serializers
from .models import Domain, WebClassification
class WebClassificationSerializer(serializers.ModelSerializer):
domains = serializers.SerializerMethodField('get_domains')
def get_domains(self, id):
return Domain.objects.filter(web_classification=id).values()
class Meta:
model = WebClassification
fields = "__all__"
并WebClassificationSerializer在視圖中使用:
# views.py
from rest_framework import generics
from .serializers import WebClassificationSerializer
from .models import WebClassification
class WebClassificationListAPIView(generics.ListAPIView):
serializer_class = WebClassificationSerializer
queryset = WebClassification.objects.all()
uj5u.com熱心網友回復:
你可以通過兩種方式做到這一點。這取決于一個人Domain可能有多個WebClassification還是只有一個:
# one Domain may have multiple WebClassifications
class WebClassification(models.Model):
...
domains = models.ManyToManyField("Domain")
# or
# one Domain may have one WebClassification
class Domain(models.Model):
...
web_classification = ForeignKey("WebClassification", on_delete=models.CASCADE, default=None, null=True, related_name="domains")
使用這兩種方法,您都可以訪問與一種方法相關的所有域WebClassification:
web_classification = WebClassification.objects.create(...)
web_classification.domains.all()
并在模板中
{{ web_classification.domains.all }}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/491618.html
標籤:Python django api django-rest-framework
下一篇:該用戶帳戶所有者的權限
