Django:更新或更改以前保存的模型数据

时间:2016-04-20 10:07:50

标签: python django database model updates

我在forms.py中有这段代码

    ref_user = User.objects.get(
    username=form.cleaned_data['referrer']
    )

    user = User.objects.create_user(
    username=form.cleaned_data['username']
    )

    # Count the referrer's direct referrals
    ref_recruits = DirectReferral.objects.filter(referrer=ref_user).count()

    # Get newly created direct referral
    get_ref = DirectReferral.objects.get(name=user)

    #Check if ref_recruits is not divisible by 2 or paired
    if ref_recruits % 2 != 0:

        # Newly created direct referral is_paired is False
        get_ref.is_paired = False
        get_ref.save()

    else:

        # Newly created direct referral is_paired is True
        get_ref.is_paired = True
        get_ref.save()

        # But I also want to update the previous is_paired to True 
        # of the same referrer
  

如何将之前的is_paired更新为同一推荐人的True?

检查下面的图片,以便更好地理解我的意思。 enter image description here 我希望你明白。

models.py(请求)

class DirectReferral(models.Model):
    name = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True)
    referrer = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="direct_referrals")
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    is_paired = models.NullBooleanField(null=False)

2 个答案:

答案 0 :(得分:2)

我认为你应该重构你的代码。根据您的实现,我相信`DirectReferral'的name字段将是唯一的。

ref_user = User.objects.get(
username=form.cleaned_data['referrer']
)

user = User.objects.create_user(
username=form.cleaned_data['username']
)

# Count the referrer's direct referrals
ref_recruits = DirectReferral.objects.filter(referrer=ref_user).count()

# Get newly created direct referral
get_ref = DirectReferral.objects.get(name=user)

#Check if ref_recruits is not divisible by 2 or paired
if ref_recruits % 2 == 0:
    get_ref.is_paired = True
    DirectReferral.objects.filter(referrer=ref_user, is_paired=False).update(is_paired=True)
else:
    get_ref.is_paired = False
get_ref.save()

答案 1 :(得分:0)

您需要以某种方式订购DirectReferral个对象,以便按正确的顺序返回它们,即最后添加的一个是DirectReferral对象列表中的第一个,然后您可以轻松更改第二个对象在列表中,在您的情况下是前一个。

例如:

get_refs = DirectReferral.objects.filter(referrer=ref_user).ordery_by('-timestamp')

if ref_recruits % 2 != 0:
    get_refs[0].is_paired = False
    get_refs[0].save()

else:
    get_refs[0].is_paired = True
    get_refs[1].is_paired = True
    get_refs[0].save()
    get_refs[1].save()