0

I know it's not true what's in the code how i can return the usernames that the api is linked to

To view in the admin page

from django.db import models
from django.contrib.auth.models import User


class api(models.Model):
    user = models.ManyToManyField(User)
    api_key = models.CharField(max_length=120)

    def __str__(self):
        return f"api key for: {self.user.username}"
Saarsa
  • 3
  • 3
  • Possible duplicate of https://stackoverflow.com/q/8001379/6842203 – Prakash S May 17 '21 at 13:00
  • Something is wrong in your implementation, you won't be able to access `self.user.username` since it's a M2M field and there won't necessary be a single user instance matching your api. – Guillaume May 17 '21 at 13:24

2 Answers2

1

You'll have to use

def __str__(self):
    return f"api key for: {[user.username for user in self.user.all()]}"

This returns all the usernames related to the ManytoManyField in a list.

eg: If you have two users with usernames austin and aron, It'll return as "api key for: ['austin', 'aron']"

ManytoManyField does not contain a single object instance, hence you cannot use self.user.username.

Ranjan MP
  • 341
  • 1
  • 6
0

If it's meant to be a ManyToManyField (i.e. you can assign multiple users to one API-key) Then you can use this:

def __str__(self):
    usernames = ', '.join(user.username for user in self.users.all())
    return f"api key for: {usernames}"
Felix Eklöf
  • 3,253
  • 2
  • 10
  • 27