外键关系;如何在Post-Django中保存

时间:2016-06-30 20:19:54

标签: django django-models django-forms foreign-keys django-views

我试图将一个条目的创建与一个帖子中的另一个模型的外来联系起来。我首先尝试使用信号进行此操作,但认为在POST期间创建关系可能更容易:

代码:

if request.POST:
    if formWG.is_valid(): 

    instance =formWG.save(commit=False)

    about = formWG.cleaned_data.get("about")
    country = formWG.cleaned_data.get("country")
    state = formWG.cleaned_data.get("state")
    city = formWG.cleaned_data.get("city")

    #instance.user = request.user
    instance.about = about
    instance.country = country
    instance.state = state
    instance.city = city
    instance.admins = [request.user.id]

    instance.save()

    groupMembers.objects.create(members = [request.user] ,createdGroupFK_id = instance.id)

    return HttpResponseRedirect(reverse('groups2:index'))

return render(request, "groups2/creategroup.html", context)

我的成员列是Int Array类型,因此我将其设置为“[request.user]”

Models.py是:

class groupCreateAndAdminAccess(models.Model):

    workGroupName = models.CharField(max_length = 80, unique=True)
    about  = models.CharField(max_length = 1000)
    interests = ArrayField(models.CharField(max_length=500, blank=True))
    country = models.CharField(max_length = 50, null=True, blank=True, default=None)
    state = models.CharField(max_length = 50, null=True, blank=True, default=None)
    city = models.CharField(max_length = 50, null=True, blank=True, default=None)
    created = models.DateTimeField(auto_now =True)

    admins =  ArrayField(models.IntegerField(default=0, null=True, blank=True),
              blank=True, null=True)


class groupMembers(models.Model):

    createdGroupFK =  models.ForeignKey(
        'groupCreateAndAdminAccess',
        on_delete=models.CASCADE,
    )

    members = ArrayField(models.IntegerField(default=0, null=True, blank=True),
              blank=True, null=True)

如果社区中的任何人可以提供帮助或指向资源。我只需要知道如何在groups表中创建组,以通过外键将自己与POST中的Group成员表相关联。或者,如果有更好的选择。

0 个答案:

没有答案