简体   繁体   中英

How to create a django model for JSONField that takes values from other fields from the same table?

I am writing a model in django which looks like this:

name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
info = JSONField()

Question: For POST request, I will provide name and address as json. Now how should I store name and address in their respective fields and store json data ie "name:{...},address:{...}" and store it into info field?

This is more or less how I create my post requests:

class MyPostView(View):
    def post(self, request):
        # Get request data
        data = json.loads(request.body)

        # Extract the values I  need
        name = data.get('name')
        address = data.get('address')

        # If the info already comes from the request do this
        info = data.get('info')

        # If you want to create the info field here do this
        info = {'name':name, 'address': address}

        # Create new model object
        new_profile = Profile()

        # Assign values
        new_profile.name = name
        new_profile.address = address
        new_profile.info = info

        # Save my object to database
        new_profile.save()

        # Return response (change this to whatever you want to return)
        return HttpResponse("Success")

Here I use class-based views but you can use function-based views the same way. I'm just not sure why you want to save the information for name and address twice.

I hope it helps!

You can override the save method, which will add those fields to your info JSONField before saving the instance.

See: Django - Overriding the Model.create() method?

Anyway I suggest you not doing so, because you are creating redundancy into columns of the very same table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM