Django Rest Framework中的多个选项

时间:2018-09-03 17:34:38

标签: django django-models django-rest-framework

class ReservationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Booking
        fields = [
            'pk',
            'persons',
            'date',
            'time',
            'table_number',
            'restaurants',
            'menu'
            ]

这是我的序列化程序类,我希望菜单字段为多个复选框字段 下面是我的模型类,这里的菜单是ManyToManyField。但是我认为这不是正确的方法。

class Booking(models.Model):
    persons = models.IntegerField()
    date = models.DateField()
    time = models.TimeField()
    table_number = models.IntegerField()
    restaurants = models.ForeignKey('sb_comp.Restraurant', on_delete=models.CASCADE)
    menu = models.ManyToManyField('sb_comp.Menu')

    def __str__(self):
        return '%s' % self.restaurants

1 个答案:

答案 0 :(得分:0)

下面是一个示例,该示例对应将哪些数据保存在数据库中进行了限制,假设如果技术员部门字段未获得在choices字段中存在的部门,则会引发异常。

   class RepairOrder(models.Model):
        '''create a repair order entry by number'''
        ro_number = models.CharField(max_length=6, help_text='Enter six digit repair order number.')
        date_added = models.DateTimeField(auto_now_add=True)
        tech = models.CharField(max_length=20, choices=TECHS, default='none',
       help_text='Technician')
        writer = models.CharField(max_length=15, choices=WRITERS, default='none',
        help_text='Service Writer')
        status = models.CharField(max_length=20, choices=STATUSES, default='unassigned',
        help_text='Work Status')
        promise_time = models.CharField(max_length=8, default='WAIT',
        help_text='Promise Time')
        job_type = models.ManyToManyField(WorkType)
        additional_details = models.TextField(null=True, help_text='Additional Information on Work to be Done')

我希望您得到图像,现在要使其成为“单选按钮”或“复选框”,您需要处理表单小部件。示例:

class SomeForm(forms.ModelForm):
    class Meta:
        model = ABC
        widgets = {'type': forms.RadioSelect}

class SomeForm(forms.ModelForm):
    some_field = forms.CharField(choices=MEDIA_CHOICES,
                                 widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = XYZ

为进一步了解,您可以看到此snippet