gpt4 book ai didi

python - 如何在保存模型之前检查ManytoMany是否有值?

转载 作者:行者123 更新时间:2023-11-30 22:54:58 25 4
gpt4 key购买 nike

假设我有两个类/模型:HandFinger。假设指纹是一个 TextField,而一只手有未知数量的手指,在 models.py 中:

from django.db import models

class Hand(models.Model):
smoothness = models.IntegerField(default=0,
validators=[
MaxValueValidator(5),
MinValueValidator(0)
])
fingers = models.ManyToManyField('Finger')
num_fingers = models.IntegerField(default=0)
has_thumb = models.BooleanField(default=False)

def save(self, *args, **kwargs):
self.num_fingers = check_num_finger() # How do I do that?
if check_has_thumb(): # How do I do that?
self.has_thumb = True
super(Hand, self).save(*args, **kwargs)


class Finger(model.Model):
is_a_thumb = models.BooleanField(default=False)
fingerprint = models.TextField()

新的 Hand 是通过 admin.py 添加的,如下所示:

from django.contrib import admin
from .models import Hand, Finger

@admin.register(Finger)
class FingerAdmin(admin.ModelAdmin):
fieldsets = [('Finger', {'fields': ['is_a_thumb','fingerprint']})]
list_display = ('is_a_thumb', 'fingerprint',)

@admin.register(Hand)
class HandAdmin(admin.ModelAdmin):
fieldsets = [('Hand', {'fields': ['smoothness']},
('Fingers', {'fields': ['fingers']}]

并且在保存Hand时,我们需要检查初始化时有多少个手指与Hand相关。还可以访问手指模型内的 is_a_thumb 字段,以从手部填充/关联 has_a_thumb

  • 如何从每个手指访问is_a_thumb,以便如果有一个手指is_a_thumb,它会更改保存之前 Handhas_a_thumb

  • 如何访问号码。分配给手指,以便我可以在保存之前更新num_fingers

最佳答案

我不确定你是否能做到before你的对象被保存。我认为这不是正确的方法。我相信你需要做的就是听 m2m_changed 发出信号并更新你的手牌。

from django.db.models.signals import m2m_changed

def fingers_changed(sender, **kwargs):
#sender Hand.fingers.through (the intermediate m2m class)
#instance hand (the Hand instance being modified)
#action "pre_add" (followed by a separate signal with "post_add")
#reverse False (Hand contains the ManyToManyField, so this call modifies the forward relation)
#model Finger (the class of the objects added to the Hand)
#pk_set finger_ids beign added (when post_add its a set of all, not the new ones only, but all)
#using "default" (since the default router sends writes here)
if kwargs['action'] == 'post_add':
hand = kwargs['instance']
hand.num_fingers = hand.fingers.count() #or len(kwargs['pk_set'])
hand.has_thumb = hand.fingers.filter(is_a_thumb=True).exists()
hand.save()

m2m_changed.connect(fingers_changed, sender=Hand.fingers.through)

注意:顺便说一句,我不确定 M2M 是否是正确的关系。是的,一只手可以有很多手指,但是一个手指只能属于一只手吗?如果这是 True 那么 mb 您需要将关系更改为一对多(手指有 FK 到手)。

关于python - 如何在保存模型之前检查ManytoMany是否有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37583355/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com