简体   繁体   English

如何在 forms.py 和 views.py 中创建冷冻 class 字段时更改父 class 中的字段?

[英]How to change a field in parent class while creating chiled class fields in forms.py and views.py?

I'm was creating ModelForm I try to make change the parent class while saving child class fields to the database, in the views.py I made but it didn't save to the database.我正在创建 ModelForm 我尝试更改父 class 同时将子 class 字段保存到数据库中,在我创建的views.py中,但它没有保存到数据库中。 here is my model.py这是我的 model.py

class Table(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    book = models.BooleanField(default=False)

class People(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
    taple = models.OneToOneField(Table, on_delete=models.CASCADE, null=True, blank=True)

@receiver(post_save, sender=User)
def update_people_profile(sender, instance, created, **kwargs):
    try:
        instance.people.save()
    except ObjectDoesNotExist:
        People.objects.create(user=instance)

Class People is the child class and Table is the parent class so I'm using People class for making forms. Class People is the child class and Table is the parent class so I'm using People class for making forms. here is my forms.py这是我的 forms.py

class Booking(forms.ModelForm):

    class Meta:
        model = People
        fields = [
            'taple',
        ]

So I want to make True book field in Table class and save it to the database when saving Booking form.所以我想在表 class中创建True book 字段,并在保存预订表单时将其保存到数据库中。 here is my views.py这是我的意见.py

def booking(request):
    if request.method == 'POST':
        try:
            people_instance = People.objects.get(user=request.user)
        except Table.DoesNotExist:
            people_instance = People(user=request.user)
        form = Booking(request.POST, instance=people_instance)
        if form.is_valid():
            user = form.save(commit=False)
            user.taple.booking = True
            user.refresh_from_db()
            user.user = request.user
            user.taple = form.cleaned_data.get('taple')
            user.save()
            print(user.taple.booking, user.taple.id)
            return redirect('booked')
    else:
        form = Booking()
    return render(request, 'main/booking.html', {'form': form})

Any Idea?任何想法?

What I understand from the snippets is that you want to be able to record if a table is booked (book Boolean Field in your Table model and if so by whom, which is the object of your People model. What I understand from the snippets is that you want to be able to record if a table is booked (book Boolean Field in your Table model and if so by whom, which is the object of your People model.

If my understanding is correct, then I don't think you really need a join table (People model).如果我的理解是正确的,那么我认为你真的不需要一个连接表(人物模型)。 Instead, I would change your model as follow:相反,我会改变你的 model 如下:

class Table(models.Model):
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
    booked_by = models.OneToOneField(User, null=True, on_delete=models.SET_NULL, related_name='table_booked')

    @property
    def is_booked(self):
        # This returns True if booked_by is set, False otherwise
        return self.booked_by_id is not None

This way you don't need the People model.这样你就不需要 People model。 The property decorator will allow you to use is_booked as a calculated field.属性装饰器将允许您使用 is_booked 作为计算字段。 Also, note the related name which will be used in the form:另外,请注意将在表单中使用的相关名称:

class BookingForm(forms.ModelForm):
    table_booked = forms.ModelChoiceField(queryset=Table.objects.filter(booked_by__isnull=True))
    class Meta:
        model = User
        fields = ['table_booked',]

In the form, you will see that we define a custom queryset for table_booked.在表单中,您将看到我们为 table_booked 定义了一个自定义查询集。 THe aim is to filter for free tables only.目的是仅过滤免费表。

Then you can hopefully simplify as well your view as follow:然后,您希望也可以简化您的视图,如下所示:

Update: As table_booked is a reverse foreign key, we actually need to save the table object which contains the relation.更新:由于 table_booked 是反向外键,我们实际上需要保存包含关系的表 object。 Here is the modified view:这是修改后的视图:

@login_required
def booking(request):
    form = BookingForm(request.POST or None, instance=request.user)
    if form.is_valid():
        user = form.save(commit=False)
        tbl = form.cleaned_data['table_booked']
        tbl.booked_by = request.user
        tbl.save()
        user.save()
        print(request.user.table_booked.id, request.user.table_booked.is_booked)
        return redirect('/')
    return render(request, 'booking/booking.html', {'form': form})

Note: I haven't tested the code so there could be some typos but that should help you getting started.注意:我还没有测试过代码,所以可能会有一些拼写错误,但这应该可以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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