Can I get third party API fields as Foreign key to my Django Model?

Viewed 138

That's true we can make foreign key relationships between models in Django. How about grabbing some fields from third party API fields as Foreign key for a specific Django model?

Here is my Django model budiness_process.py

class BusinessImpact(models.Model, ModelWithCreateFromDict):

client = models.ForeignKey(
    accounts_models.Client, on_delete=models.CASCADE)
business_process = models.ForeignKey(
    BusinessProcess, on_delete=models.CASCADE)
hierarchy = models.CharField(max_length=255)
business_assets = models.CharField(max_length=255)
asset_name = models.CharField(max_length=255)
vendors = models.CharField(max_length=255)
product = models.CharField(max_length=255)
version = models.CharField(max_length=10)
cpe = models.CharField(max_length=255)
asset_type = models.CharField(max_length=10)
asset_categorization = models.CharField(max_length=255)
asset_risk = models.CharField(max_length=50)
_regulations = models.TextField(blank=True)
_geolocation = models.TextField(blank=True)

def __str__(self) -> str:
    return self.hierarchy + " - " + self.business_assets

Here is my serializer.py

class BusinessImpactSerializer(serializers.ModelSerializer):
business_process = BusinessProcessListSerializer()
class Meta:
    model = models.BusinessImpact
    fields = "__all__"

Here is third API implementation for retrieving some of it's fields.

 @api_view(
    ["GET"],
)
def cve_summery(request, key):
    r = requests.get(
        "https://services.nvd.nist.gov/rest/json/cves/1.0?cpeMatchString={}".format(
            key)
    )
    if r.status_code == 200:
        result = []
        res = r.json().get("result").get("CVE_Items")
        for rs in res:
            data = {
                "VulnID": rs.get("cve").get("CVE_data_meta").get("ID"),
                "Summery": rs.get("cve").get("description").get("description_data"),
                "exploitabilityScore": rs.get("impact")
                .get("baseMetricV2")
                .get("exploitabilityScore"),
                "severity": rs.get("impact").get("baseMetricV2").get("severity"),
                "impactScore": rs.get("impact").get("baseMetricV2").get("impactScore"),
            }
            result.append(data)
        return Response(result)
    return Response("error happend", r.status_code)

So my intention here is, can I get "severity": rs.get("impact").get("baseMetricV2").get("severity") as Foreign key in my BusinessImpact model?

Thanks!

1 Answers

The meaning of a foreign key is to link tables at a DB level, so you can not have a ForeignKey field if the data coming from your third party API is not stored on your side.
You could however store this info in your model, inside a required field, and validate the value when saving your instance.
This way you could be sure that the key is valid and could be used later on to request the API.

Related