SihwanLee
SihwanLee

Reputation: 169

How to check the variables passing through the model class in Django?

I have a code as the following:

# models.py

class UserFollower(models.Model):
    user_id = models.ForeignKey(CustomUser, related_name="following", on_delete=models.CASCADE)
    following_user_id = models.ForeignKey(CustomUser, related_name="followers", on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True, db_index=True)

    def __str__(self):
        return f"{self.user_id} follows {self.following_user_id}"

Now here, I want to check when the data is passed, if the user_id equals the following_user_id, it will output a message saying "It isn't possible" and not save the model. Of course later in the development, I wouldn't have the "Follow" button or something like that associated with the same user, but in this case, how would I do so?? Or is it something I can't do in the models.py and do it in the views.py?

Upvotes: 0

Views: 185

Answers (1)

Nicolas Appriou
Nicolas Appriou

Reputation: 2331

You want to do model validation.

class UserFollower(models.Model):
    user_id = models.ForeignKey(CustomUser, related_name="following", on_delete=models.CASCADE)
    following_user_id = models.ForeignKey(CustomUser, related_name="followers", on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True, db_index=True)

    def clean(self):
        if user_id_id == following_user_id_id:
            raise ValidationError("User ID is the same as following_user")

Btw, you foreign key should not have the _id prefix. When you ask for a foreign key field of a model, you get an instance of the linked model. If you add _id to the name of the field, you get the id of the linked instance. (this is why I put _id_id on the example fields).

class MyModel(models.Model):
    linked_item = models.ForeignKey(OtherModel, ...)


foo = MyModel.objects.get(pk=1)
foo.linked_item  # is an instance of OtherModel
foo.linked_iutm_id  # is an integer

Upvotes: 1

Related Questions