I am using django-rest-framework to build out the back end. I have the list running fine, but (using the django-rest-framework admin screen) I cannot create an object by just using the Id fields of the foreign key objects. I hope I have this configured incorrectly, but I am open to writing some code if i have to :) I am learning django/python from a .NET and Java background and may have become a touch spoiled by this new stack.
Edit: I am trying not to use two different Model classes- I shouldn't have to right?
Thanks in advance.
From Chrome - the key bits of the request
Request URL:http://127.0.0.1:8000/rest/favorite_industries/
Request Method:POST
_content_type:application/json
_content:{
"user_id": 804 ,"industry_id": 20 }
The response
HTTP 400 BAD REQUEST
Vary: Accept
Content-Type: text/html; charset=utf-8
Allow: GET, POST, HEAD, OPTIONS
{
"user": [
"This field is required."
]
}
Ugh. Here are the key classes from django:
class FavoriteIndustry(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(User, related_name='favorite_industries')
industry = models.ForeignKey(Industry)
class Meta:
db_table = 'favorites_mas_industry'
class FavoriteIndustrySerializer(WithPkMixin, serializers.HyperlinkedModelSerializer):
class Meta:
model = myModels.FavoriteIndustry
fields = (
'id'
, 'user'
, 'industry'
)
Edit Adding the viewset:
class FavoriteIndustriesViewSet(viewsets.ModelViewSet):
#mixins.CreateModelMixin, viewsets.GenericViewSet):
paginate_by = 1
queryset = myModels\
.FavoriteIndustry\
.objects\
.select_related()
print 'SQL::FavoriteIndustriesViewSet: ' + str(queryset.query)
serializer_class = mySerializers.FavoriteIndustrySerializer
The get/list functionality generates decent JSON:
{"count": 2, "next": "http://blah.com/rest/favorite_industries/?page=2&format=json", "previous": null, "results": [{"id": 1, "user": "http://blah.com/rest/users/804/", "industry": {"industry_id": 2, "industry_name": "Consumer Discretionary", "parent_industry_name": "Consumer Discretionary", "category_name": "Industries"}}]}
I have created a simplified mock up of your application.
models.py:
views.py:
serializers.py:
urls.py:
And here are a few tests:
Django REST Framework expects
user
andindustry
fields as URLs rather than ids since you are usingHyperlinkedModelSerializer
.Using IDs
In case you need to use object ids instead of URLs, use
ModelSerializer
instead ofHyperlinkedModelSerializer
and pass ids touser
andindustry
:serializers.py:
And tests:
This will do it. But I think the django-rest-framework should provide this plumbing for me, so please follow up with any better answers