简体   繁体   中英

Retrieve data from django-rest to show in a form

I have two classes linked with a ForeignKey. My first class is "Categories", with "ID" and "Name" properties. The second class is "Documents", with "ID", "Title" and "User" properties, the last one is linked with a category defined in the first class.

I'm developing the front-end based on Vue, so I want to know how to retrieve data from django-rest to show it in a form. For example, when a user adds a new doc, he must choose between all category options. Note that categories will be common to all documents.

Example: Categories = [{"ID": 0, "Name "Sports"}, {"ID": 1, "Name": "Music"}]

Form to add a new document:

Title: XXXX

Category:
Sports,
Music

models.py


from django.db import models

class Category(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)

class Documents(models.Model):
    id = models.AutoField(primary_key=True)
    title= models.CharField(max_length=200)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

I think that if I get a answer like below it will resolve my problem.

["docs": 
     [{"ID": 1, "Title": "Doc1", "Category": Sports}, 
     {"ID": 2, "Title": "Doc2", "Category": Music}], 
 "categories": 
     [{"ID": 0, "Name: "Sports"}, 
     {"ID": 1, "Name": "Music"}]

不知道Vue,但是您可以通过GET请求获取所有类别,然后使用这些类别作为选项填充下拉菜单,并获得提交时的下拉菜单值。

You could make a separated request to get all the category before you create the form.

To do this, you need to create a CategorySerializer and a ListCategoryProvider

class CategorySerializer(serializers.ModelSerializer):

    class Meta:
        model = Category
        fields = {'name'}

class ListCategoryProvider(generics.ListAPIView):
    serializer_class = CategorySerializer

    def get_queryset(self):
        queryset = Category.objects.all()
        return queryset

Then you need to parse the JSON containing all the categories names, to display them in your form

1) write a serializer in the Django rest for category and document. Please go through the link for serializer https://www.django-rest-framework.org/api-guide/serializers/

2) write a form in html where you can insert the document. In the javascript(vue), you can call ajax request(get request) for the category and display the category's in select options.

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