I'm having trouble adding to tag field through many to many relationship on article object.
I'm able to replace all current article.tags by passing HTTP method of PATCH.
However, I would like to add to the existing relationships on article.tags, rather than replacing.
I cannot find a built in way to do this. Am I missing something obvious?
My article modedel serializer has the following field:
tags = serializers.PrimaryKeyRelatedField(many=True)
In your 'article' model serializer instead of
tags = serializers.PrimaryKeyRelatedField(many=True)
use the below code
tags = TagSerializer()
here 'TagSerializer' is the model serializer of 'Tag' model like
class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
Related
I'm fairly new to django and i would need your help!
I wrote an api/route view that query the database and return a JSON to my fetch function in my javascript.
Is there a way to query the database and got back a queryset with foreign key replaced by its associated value ?
I though i could use ModelName.objects.select_related( 'field ') but i didn't understand how it works.
If you have a solution or advices on better way to achieve the goal, Thanks in advance!
Context in pseudo-code:
// HTML //
Button onclick function get_list_of_data
// JS //
function get_list_of_data:
Fetch URL of route django
Convert response to JSON
iterating through JSON to fill HTLM div
// Django //
use ModelName.objects.filter( name = name ) to get list of data in Queryset
use serializers.serialize(json, ...") to get JSON from Queryset
return JsonResponse (json_query)
If I understood the problem well, when you serialize a model that has a ForeignKey field defined you get only the id value in JSON response but you would like to get the whole object (not only a number) returned.
The way to do that is to specifically write serializer for that ForeignKey model and then use it within the serializer od the model that you are trying to fetch.
You haven't provided any code, but here is some example that might help you:
class SecondModelSerializer(serializers.ModelSerializer):
class Meta:
model = SecondModel
fields = '__all__'
class FirstModelSerializer(serializers.ModelSerializer):
foreign_key_field = SecondModelSerializer()
class Meta:
model = FirstModel
fields = ('id', 'foreign_key_field', 'field1', 'field2')
Here in your FirstModelSerializer you specifically told Django to use SecondModelSerializer for your ForeignKey field (I named it foreign_key_field). This way Django will know how to serialize that field instead of returning only the id value.
I am using a nested serializer. I need ProfileSerializer to return full related Project object for get requests and consider only id switching (changing current) like with relatedPrimaryField behaiviour for post/put requests on ProfileSerializer. any solutions on how to achieve this ?
class ProfileSerializer(serializers.ModelSerializer):
current = ProjectSerializer()
class Meta:
model = Profile
fields = ('function', 'current')
As Linova mentioned, the easiest way to solve this issue without using a third-party library is to declare two separate fields in your serializer. Your nested serializer current would stay the same, but you would add a new PrimaryKeyRelatedField serializer. The nested serializer should be read only, but the related field would not be read only. I normally name the related field <field>_id by convention.
In GET requests, both the nested serializer and the id field will be returned, but for PUT or POST requests only the <field>_id needs to be specified.
class ProfileSerializer(serializers.ModelSerializer):
current = ProjectSerializer(read_only=True)
current_id = serializers.PrimaryKeyRelatedField(queryset=Projects.objects.all(), source='current')
class Meta:
model = Profile
fields = ('function', 'current', 'current_id')
The most consistent way I usually advice is to mark all the nested serializer (ProjectSerializer in this case) as read_only and add the id field as read_only=False
You'll therefore have consistence between the list/retrieve and creation/updates.
In Django Rest Framework, what's the appropriate way to write a hyperlinked serializer for a model that has a property that points to a reverse related object or None?
class AModel(models.Model):
a_name = models.CharField()
#property
def current_another_model(self):
# Just an example, could be whatever code that returns an instance
# of ``AnotherModel`` that is related to this instance of ``AModel``
try:
return self.another_model_set.objects.get(blah=7)
except AnotherModel.DoesNotExist:
return
class AnotherModel(models.Model):
blah = models.IntegerField()
our_model = models.ForeignKey(AModel)
How do we write a serializer for AModel that contains the url (or null, of course) for the property current_another_model?
I've tried this (I have a working AnotherModel serializer and view):
class AModelSerializer(serializers.HyperlinkedModelSerializer):
current_another_model = serializers.HyperlinkedRelatedField(read_only=True, view_name='another-model-detail', allow_null=True)
That gets me this error:
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "another-model-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
Define AnotherModel serializer and define that dependency within AModelSerializer, also add class Meta in your AModelSerializer.
class AModelSerializer(serializers.ModelSerializer):
current_another_model = AnotherModelSerializer(allow_null=True, required=False)
class Meta:
model = AModel
fields = ('current_another_model',)
That code should do the trick for you.
Another way is stick to the official documentation while defining related serializers.
Update: Found quite similar question Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"
which is solved.
I'm writing a simple scaffolding app in django, however I'm still not able to access a models fields and attributes(e.g. CharField, max_length=100, null=True, etc...). I know about the _meta class of models, but as far as I know it only retrieves basic info about the model not the fields. Is there a away to achieve this?
Update:
you can find the answer in this article:
http://www.b-list.org/weblog/2007/nov/04/working-models/
You should use the get_field method to get info for a particular field:
field = ModelName._meta.get_field('field_name')
Then you may check various attributes of field, like field.blank, field.null, field.name etc.
If on the other hand you want to get a list of all fields of a Model you should use fields:
fields = ModelName._meta.fields
For example to get the name of all your model fields you can do something like:
field_names = ', '.join(f.name for f in fields)
Hm... also I just noticed that your question is a duplicate of Get model's fields in Django !
I use the django comments from contrib and I have an object (entry) that has some comments associated with it. In my tastypie resources I have:
class CommentResource(ModelResource):
user = fields.ForeignKey(UserResource, 'user')
class Meta:
queryset = Comment.objects.all()
resource_name = 'comments'
allowed_methods = ['get']
fields = ['comment', 'resource_uri', 'submit_date', 'user',]
filtering = {
'user': ALL_WITH_RELATIONS,
}
and I can get all the comments, or filter them by user. It's working ok.
Now I'm not sure, how would I do the same kind of filter but based on a certain entry object instead of user?
Thanks for your help.
Without knowing what is the relationship between the entry and comment it is hard to give a concrete answer but in a nut shell given that entry and comments are linked via manytomany relationship:
Create an EntryResource
Add the fields.ToManyField to the EntryResource for CommentResource
Add the `fields.ToOneField' to the CommentResource for EntryResource
Add 'comments' : ALL_WITH_RELATIONS to the filtering dict in EntryResource
Additionally, you could add a nested resource or a custom URL to the Comment to filter them based on an entry, but it all depends on your design.
Almost verbatim example for the above is given in Tastypie docs here.