Jayaram
Jayaram

Reputation: 6606

ManytoManyField not returning str object

I have the 2 below models.

class Customer(models.Model):
    Customer = models.OneToOneField(User)
    CustomerID = models.CharField(max_length = 15)


    def __str__(self):
        return self.Customer.username


class Customer_Coupons(models.Model):

    Customer_Det = models.ManyToManyField(Customer)
    Campaign_Det = models.ManyToManyField(Campaigns)
    Redeemed = models.BooleanField(default = False)

    def Get_Customer_ID(self):
        return '\n'.join([p.CustomerID for p in self.Customer_Det.all()])

    def Get_Campaign_ID(self):
        return '\n'.join([p.CampaignID for p in self.Campaign_Det.all()])

    def __str__(self):
        return self.Customer_Det.CustomerID

I'm having a problem with the str method for Customer_wallet. I seem to be getting the below error when querying. Is there a better way to define the str method? I would preferably want a CustomerID or the Customer name which is again stored in a User table.

TypeError: __str__ returned non-string (type ManyRelatedManager)

Upvotes: 2

Views: 1165

Answers (1)

301_Moved_Permanently
301_Moved_Permanently

Reputation: 4186

Your Customer_Coupons.Customer_Det field is a ManyToManyField, thus self.Customer_Det does not denote a single value.

You may want to iterate over all possible Customer.CustomerID in self.Customer_Det to build the return string. Or just use the first one you encounter, or whatever suits your needs.

Try:

return ' / '.join(cust.CustomerID for cust in self.Customer_Det.all())

Change all for filter or get depending on your needs.


Edit

It appears, from the comments, that you expect your Customer_Coupons model to have each instances related to 1 customer and 1 campaign at a time. In this case, use a ForeingKey field for both of them instead of a ManyToManyField. You will be able to access the related object fields the same way you are trying to in your question (i.e. self.Customer_Det.CustomerID).

If you need to have your coupons following both:

  • Users can have several coupons;
  • Coupons can belong to several users.

then do not expect instances of Customer_Coupons to relate to only 1 customer. Same goes for campaigns.

Upvotes: 2

Related Questions