Save a list in the Django database

How do I save a list in a Django database? What type of field do I use pls?

If I cannot save the list in a field then how do i convert it to something I can save. It’s a simple list of integers 7 number between 1 and 10

[5, 2, 8, 3, 9, 1, 5]

I tried a big integer field but that does not accept a list.

postgre supports this?
Otherwise a JSON field? → Model field reference | Django documentation | Django

… or a many to many relationship? (might not be relevant at all!)

ok but this sounds all so complicated. I simply want to save the numbers in the list not necessarily the list itself. It can be a string it really doesn’t matter. How can I convert that list to a string pls?

“ok but this sounds all so complicated”. Really?

then basic python:

','.join(str(x) for x in [1, 2, 3, 4, 5])

and that’s it.

Yes thank you really simple, yet the value is not being saved in my user model.

User model:

from django.db import models
from django.contrib.auth.models import (
    AbstractBaseUser,
    BaseUserManager,
    PermissionsMixin,
)


class UserManager(BaseUserManager):
    def create_user(self, email, password, confirm_code=None,username=None, role=None, ):
        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, role, username=None):
        user = self.model(email=self.normalize_email(email))
        user.set_password(password)
        user.role = role
        user.is_staff = True
        user.is_active = True
        user.is_superuser = True
        user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    EM = "EM"
    SM = "SM"
    DH = "DH"
    ROLES = [
        (EM, "Executive Management"),
        (SM, "Senior Management"),
        (DH, "Department Head"),
    ]

    objects = UserManager()
    role = models.CharField(max_length=2, choices=ROLES, default=US, blank=True)
    username = models.CharField(max_length=20, unique=True, blank=True, null=True)
    email = models.EmailField(max_length=255, unique=True)
    slug = models.SlugField(blank=True, null=True)
    confirm_code = models.CharField(max_length=10, null=True, blank=True)
    is_active = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    has_profile = models.BooleanField(default=False)
    email_verified_at = models.DateTimeField(auto_now=False, null=True, blank=True)
    code = models.CharField(max_length=8, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at")

    class Meta:
        verbose_name = "User"
        verbose_name_plural = "Users"
        ordering = ["username"]
        db_table = "users"

    def get_absolute_url(self):
        return f"{self.slug}"

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = ["role"]

and here is the view used to register a user with:

code = []
numbers = range(7)
for num in numbers:
    code.append(randint(0, 9))

@api_view(["POST"])
def RegisterUser(request, *args, **kwargs):
    email = request.data["email"]
    confirmemail = request.data["confirmemail"]
    password = request.data["password"]
    confirmpassword = request.data["confirmpassword"]
    errors = []
    if email != confirmemail:
        errors.append("emailmatch")
        return Response("Emails do not match", status=500)
    if confirmpassword != password:
        errors.append("passmatch")
        return Response("Password do not match", status=500)
    if User.objects.filter(email=email):
        errors.append("emailexists")
        return Response("User is already registered", status=500)
    else:
        pass
    if len(errors) > 0:
        return Response(False)
    else:
        password_to_save = make_password(password)
        confirm_code = " ".join(str(e) for e in code)
        user = User.objects.create_user(
            email=email, password=password_to_save, confirm_code=confirm_code
        )
        user.save()
        token = Token.objects.create(user=user)
        from_email = "info@website.com"
        link = f"http://127.0.0.1:8000/api/v1/users/confirm/{user.id}/{token}/"
        context = {"link": link, "code": code}
        template = get_template("emails/welcome.html").render(context)

        subject = "Successfully registered"
        message = "Welcome to website"

        try:
            send_mail(
                subject,
                message=message,
                from_email=from_email,
                recipient_list=[email],
                html_message=template,
            )
        except:
            return Response("Could not send mail")

        serializer = RegisterSerializer(user)

        return Response(serializer.data)

any idea why not?

Nevermind I solved it

ok great-- although I wonder about this:

code = []
numbers = range(7)
for num in numbers:
    code.append(randint(0, 9))

Since this sits outside of the view in itself … it will I think always be the same for all users (ie., generated at startup of your application)? Unless you do something with code further down in the view?

Thank you I was actually wondering about that cause I got the same number a few times in a row. You helped me here thank you so much

`#models.py
class Main_search(models.Model):
    name = models.CharField(max_length=255, null=True)
    model = models.CharField(max_length=50, null=True)
    list_id = models.TextField(null=True)  #list 1000, 20000 and more

#views.py
import json

model = 'Paym_doc'
search = '123456'
list_id = [1, 3, 8]
search_id = Main_search.objects.create(name=search, list_id=json.dumps(list_id), model=model).id

#*
jsonDec = json.decoder.JSONDecoder()
rec = Main_search.objects.get(id=search_id)
list_id = jsonDec.decode(rec.list_id)
`