【发布时间】:2018-06-16 07:39:12
【问题描述】:
是否可以制作一个使用 REST API 作为外键的模型字段?
我有两个项目。第一个项目在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)])
我在 serializers.py 中使用以下代码对模型进行了序列化:
from rest_framework import serializers
from currencies . models import Currency
class CurrencySerializer(serializers.ModelSerializer):
class Meta:
model = Currency
fields = ('name', 'code')
我创建了以下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)
并在 urls.py 中提供以下内容:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^currencies/$', views.currency_list),
]
URL 以 JSON 格式传递信息正常。没有身份验证(我还不够好)。当我使用 requests 库并发出 get 请求时,它返回以下内容:
[{"name": "Krone", "code": "DKK"}, {"name": "Pound Sterling", "code": "GBP"}, {"name": "Cedi", "code": "GHS"}]
我想在一个新项目中使用这些信息,该项目将有一个不同的数据库并使用以下模型发布记录:
class JournalEntry(models.Model):
date = DateField()
currency = ForeignKey(consuming the json data so it renders as a dropdown menu in html)
value = IntegerField()
有没有一个好方法来做这样的事情?我还没有找到任何可以帮助我正确概念化这一点的回应。也是为了帮助我学习。我打算用这种基于 API 的方法来实现更复杂的项目。谢谢。
【问题讨论】:
-
在您的第二个项目中(定义了
JournalEntry),您不能访问第一个项目的Currency模型吗?我的意思是...你不能按照currency = ForeignKey('other_project.Currency...)`的方式做点什么吗? -
我认为当一切都在我的计算机上时,您的方法效果很好。当我将项目 1 部署到 Elastic Beanstalk 时,我担心如何访问它的数据。我将在生产中试用它并回复您。感谢您的评论。我非常感激。
标签: python json django rest django-rest-framework