Ion Aag
Ion Aag

Reputation: 53

Checking for object if it already exists in manytomany field

I am trying to give a status of "Already Exists" if a customer already exists in the manytomany field of Customers

View Class:

class CustomerAddition(View):
    def get(self, request, business_id, user_id):
        current_business = Business.objects.get(pk=business_id)
        customer = User.objects.get(pk=user_id)
        new_customer, created = Customers.objects.get_or_create(business_id_id = business_id)
        new_customer.save()
        list_of_customers = Customers.objects.get(business_id_id = business_id).customers.all()
        for value in list_of_customers:
            print(value)
            if value == User.objects.get(pk=user_id).name:
                return JsonResponse({"Status":"Already Exists"})
        new_customer.customers.add(customer)
        new_customer.save()

        return JsonResponse({"Status":"Success"})

Model:

class Customers(models.Model):
     customers = models.ManyToManyField('User')
     business_id = models.ForeignKey(Business, on_delete = models.CASCADE, related_name='owner')

     def __str__(self):
         return 1

Whenever I call the API with the same customer, it's always giving a status of "Success"

Print(value) result :

Sagar Aggarwal
Kartik Luthra

Upvotes: 0

Views: 516

Answers (1)

adnanmuttaleb
adnanmuttaleb

Reputation: 3624

you are comparing User object to User's name (string).

value == User.objects.get(pk=user_id).name

which will fail always.Try this:

value.name == User.objects.get(pk=user_id).name

Upvotes: 1

Related Questions