Is it possible to make a model field that consumes a REST API as a foreign key?
I have two projects. The first project has this model in models.py:
from django.db import models
from django_countries.fields import CountryField
from django.urls import reverse
class Currency(models.Model):
name = models.CharField(max_length = 50)
country = CountryField()
code = models.CharField(max_length = 3)
base = models.BooleanField()
class Meta:
ordering = ['code']
def __str__(self):
return (self.code)
def get_absolute_url(self):
return reverse('currency_detail', args = [str(self.id)])
I have serialized the model with the following code in serializers.py:
from rest_framework import serializers
from currencies . models import Currency
class CurrencySerializer(serializers.ModelSerializer):
class Meta:
model = Currency
fields = ('name', 'code')
I created the following views.py:
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from currencies . models import Currency
from . serializers import CurrencySerializer
def currency_list(request):
currency = Currency.objects.all()
serializer = CurrencySerializer(currency, many = True)
return JsonResponse(serializer.data, safe = False)
and provided the following in urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^currencies/$', views.currency_list),
]
The URL is passing the information ok in JSON format. There are no authentications (I am not good enough yet). When I use the requests library and make a get request, it returns the following:
[{"name": "Krone", "code": "DKK"}, {"name": "Pound Sterling", "code": "GBP"}, {"name": "Cedi", "code": "GHS"}]
I would like to consume this information in a new project which will have a different database and post records with the following model:
class JournalEntry(models.Model):
date = DateField()
currency = ForeignKey(consuming the json data so it renders as a dropdown menu in html)
value = IntegerField()
Is there a good way to do something like this? I haven't found any responses that help me conceptualize this properly. Also it is to help me with my learning. I intend to implement more complicated projects with this API-based approach. Thanks.
JournalEntryis defined), don't you have access to theCurrencymodel of the first project? I mean... Can't you do something along the linescurrency = ForeignKey('other_project.Currency...)`?