简体   繁体   中英

Using parameters in create viewset?

In a specific usecase of my application, I would like to do some logic (varies based on what the user chooses - and thus passed through via the API url) in order to create and return a model.

In my application I have a simple test model and question model (each question has a concept:

class Question(models.Model):

    text = models.CharField(max_length=255, null=False)
    concept = models.CharField(max_length=255, null=False)


class Test(models.Model):

    num_questions = models.IntegerField()
    questions = models.ManyToManyField(Question)

I hoped that user would be able to do a create as such XXX/api/v1/test/create/Math and this would return them a test with questions randomly chosen that pertain to math.

in my url I have explicitly called out path('test/create/<str:concept>', CreateTestView.as_view(), name="test-create="),

However, when I try and reference this, it does not allow me to pass it in (erroring out with concept is not defined):

class CreateTestView(generics.ListCreateAPIView, concept):

    test = Test()

    ... add random questions to test

    queryset = test
    serializer_class = TestSerializer

If you mean that you want to use the <str:concept> param. You need to specify that param in the method definition of the view (post, get, patch,...) where you want to use that parameter.

class CreateTestView(generics.ListCreateAPIView):

    def post(self, request, concept, *args, **kwargs):
        # use concept param

    def get(self, request, concept, *args, **kwargs):
        # use concept param

    def patch(self, request, concept, *args, **kwargs):
        # use concept param

    # all the methods where you want to use the concept param

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