Make model field unique for user

(Erik Brown) #1

I’m curious about the recommended way to force a field to be unique for each user. That is, I have a model with a user foreign key, a description field, and other fields. I want the description field to be unique for the user. That is, two users can have the same exact description field, but the description fields for a specific user must be unique.

I currently check this in my View class as part of the post() method, but I keep wondering if I should be doing this in my model or form. Here is an excerpt of how this is currently working:

class MyModelView(View):
def post(self, request):
form = MyModelForm(request.POST)

if form.is_valid()
  obj =

  # make sure description is unique for this user
  user_descriptions = MyModel.objects.filter(user=request.user)
  if user_descriptions.filter(description=obj.description):
    # description already exists, insert an error
    form.add_error('description', 'You already have a MyModel with this description, please use something else')
    # ready to add the new object
    obj.user = request.user

    return redirect('object_list')
  # end if-else

return render(request, 'myapp/myobj_add.html', {'form': form })

Appreciate any insight.


(Mit Patel) #2

Insted of giving the ForeignKey give the relation onetoone filed in models,so the each user have only one description object to relate:
class UserDescription(models.model):
user=models.OneToOneField(“Your user table”);
and rest of your other filed is goes here

(Erik Brown) #3

Thanks for the comment, Mit, appreciate it.

My understanding for OneToOne is that you have exactly one description per user, which is not what I’m looking for. Think, for example, of houses. Each user can have multiple houses, and each user can have a “Home” house and “Vacation” house and so forth. However, one user cannot have two houses called “Home” or “Vacation.”

So when a user creates a new house, and they call it “Vacation,” I want to verify that that specific user doesn’t already have a house called “Vacation.” I’m enforcing this successfully in the view right now, and curious if there is a better way to do this in the model or form. One issue I have is that the Form and Model don’t necessarily know who the current user is directly. But in the View I have this directly.

Thanks again,