DRF how to save a model with a foreign key to the User object

久未见 提交于 2021-02-07 19:59:20

问题


I have the following model:

class Journal(models.Model):
    project_name = models.TextField()
    intro = models.TextField(blank=True)
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    creator = models.ForeignKey(User)
    group = models.OneToOneField(Group)
    contact_info = models.TextField(blank=True)
    allow_anon = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)

I would like to save a record of this model when users submit a form. The values of all the required fields are submitted along with the form so I assume request.data would have them in it except for the creator field.

Since I use token authentication, a token that can identify the user is passed within the HTTP header. According to this post, I can use request.META('whatever') to pull out this token key from the header. Then I will be able to retrieve the user instance based on the token.

So far so good, my question is the next step, how can I write a serializer that can take request.data and a user instance when saving?

I think I should use a ModelSerializer based on the model defined above. But how can I turn the user instance into a serializable form so that the ModelSerializer can consume while saving?


回答1:


When you're correctly authenticated by token, then you should have a user attribute available in request object.

So depending where you add the logic for passing user object, you can have it in the generic view:

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

or inside serializer (assuming your view is passing context):

def create(self, validated_data):
    data = validated_data.copy()
    data['user'] = self.context['request'].user

    return super(JournalSerializer, self).create(data)



回答2:


This should work.

data = request.data
data['creator'] = user_id  # fetch user_id from metadata first
serializer = YourSerializer(data=data, partial=True)
if serializer.is_valid():
    serializer.save()

Please comment if you need any further clarification , or face any issues.



来源:https://stackoverflow.com/questions/34018110/drf-how-to-save-a-model-with-a-foreign-key-to-the-user-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!