开启代码之旅 Launch With Code


1278 浏览 6 years, 1 month

13 Save Reference ID with Foreign Key Model Fields

版权声明: 转载请注明出处 http://www.codingsoho.com/

添加Friend,用reference id作为索引

  • 在join model中添加friend字段
  • 在view中将join object存为friend
class Join(models.Model):
    email =  models.EmailField()
    friend = models.ForeignKey("self", related_name='referral', null=True, blank=True)
    ref_id = models.CharField(max_length=120, default='ABC', unique=True)
    ip_address =  models.CharField(max_length = 120, default = 'ABC')
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)
    def __unicode__(self):
        return "%s %s" %(self.email, self.ref_id)

    class Meta:
        unique_together = ("email", "ref_id",)
def home(request):
    try:
        join_id = request.session['join_id_ref']
        obj = Join.objects.get(id=join_id)
    except:
        obj = None  
    form = JoinForm(request.POST or None)
    if form.is_valid():
        new_join = form.save(commit = False)
        email = form.cleaned_data['email']
        new_join_old, created = Join.objects.get_or_create(email = email)
        if created:
            new_join_old.ref_id = get_ref_id()
            if not obj == None:
                new_join_old.friend = obj
            new_join_old.ip_address = get_ip(request)
            new_join_old.save()
        return HttpResponseRedirect("/%s" %(new_join_old.ref_id))       
    context = {"form":form}
    template = "home.html"
    return render(request, template, context)