Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango-Rest-Framework updating a foreign key BY Id
    primarykey
    data
    text
    <p>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.</p> <p><strong>Edit: I am trying not to use two different Model classes- I shouldn't have to right?</strong></p> <p>Thanks in advance.</p> <p>From Chrome - the key bits of the request</p> <pre><code>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 } </code></pre> <p>The response</p> <pre><code>HTTP 400 BAD REQUEST Vary: Accept Content-Type: text/html; charset=utf-8 Allow: GET, POST, HEAD, OPTIONS { "user": [ "This field is required." ] } </code></pre> <p>Ugh. Here are the key classes from django:</p> <pre><code>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' ) </code></pre> <p><strong>Edit Adding the viewset:</strong></p> <pre><code>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 </code></pre> <p>The get/list functionality generates decent JSON:</p> <blockquote> <p>{"count": 2, "next": "<a href="http://blah.com/rest/favorite_industries/?page=2&amp;format=json">http://blah.com/rest/favorite_industries/?page=2&amp;format=json</a>", "previous": null, "results": [{"id": 1, "user": "<a href="http://blah.com/rest/users/804/">http://blah.com/rest/users/804/</a>", "industry": {"industry_id": 2, "industry_name": "Consumer Discretionary", "parent_industry_name": "Consumer Discretionary", "category_name": "Industries"}}]}</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload