37

フォーム入力からユーザーと製品のデータを保存する django モデルがあります。

def ProductSelection(request, template_name='product_selection.html'):
    ...
    if user.is_authenticated():
        user = request.user
    else:
        # deal with anonymous user info
    project = Project.objects.create(
        user=user,
        product=form.cleaned_data["product"],
        quantity=form.cleaned_data["product_quantity"],
    )

もちろん、これは認証されたユーザーには問題ありませんが、匿名ユーザーのプロジェクトを保存し、可能であれば、最終的に登録して認証するときにそれらをユーザーに関連付けたいと考えています。

私の考えは、name = some_variable (ランダムなハッシュと連結されたタイムスタンプ?) で匿名ユーザーを作成し、そのユーザー名をセッション データに保存することです。そのセッション変数が存在する場合、そのユーザーのすべてのプロジェクト アクティビティを記録するために使用されることを確認すると、登録時にユーザーの実際の資格情報でプロジェクトを更新できるはずです。

これは過度に複雑で脆いですか?何千行ものデータを不必要に保存するリスクはありますか? この一般的な問題に対する最適なアプローチは何でしょうか?

これに関するガイダンスは大歓迎です。

4

2 に答える 2

30

Django のセッション フレームワークを使用して、匿名のユーザー データを格納できます。

Project次に、モデルにフィールドを追加してsession_key、匿名ユーザーの値を保持するか、

project = Project.objects.create(
    user=request.user,  # can be anonymous user
    session=request.session.session_key,
    product=form.cleaned_data["product"],
    quantity=form.cleaned_data["product_quantity"])

または、Project インスタンスがセッションに持つすべてのデータを単純に保存します。

if user.is_authenticated():
    project = Project.objects.create(
        user=request.user,
        product=form.cleaned_data["product"],
        quantity=form.cleaned_data["product_quantity"])
else:
    # deal with anonymous user info
    request.session['project'] = {
        "product": form.cleaned_data["product"],
        "quantity": form.cleaned_Data["product_quantity"]}

後で適切なユーザーを作成するときに、セッションからデータを取得できます。

于 2012-12-18T18:50:35.807 に答える
11

明確にするために、以下のコードは私の場合のソリューションの実装方法です。

        project = Project.objects.create(
            session=request.session.session_key,
            # save all other fields
            ...
        )
        if request.user.is_authenticated():
            project.user = request.user
        else:
            # make a copy of the session key
            # this is done because the session_key changes
            # on login/ register 
            request.session['key_copy'] = request.session.session_key
        project.save()

そして私のmodels.pyで:

 class Project(models.Model):
     user = models.ForeignKey(User, null=True, blank=True)
     ...

したがって、ユーザー フィールドは null になる可能性があり、この場合、session_key を使用して物事を追跡します。

于 2012-12-20T21:12:34.527 に答える