R
R
r1mple2022-04-05 01:51:43
Django
r1mple, 2022-04-05 01:51:43

How, when creating a User object in the database, create another object, such as a Promo Code?

That is, there is a User object, when the user writes / start to the bot, it enters the database.
The ratio is 1 to 1, those are only one unique promotional code for one unique user.
When creating this user object, how can I also create a Promotional Code object, and write this promotional code in the pane from the user fields?
I have a solution in my head, but it is a crutch, in any case there is some simple solution.
current code

class UserModel(models.Model):
    userStatuses = (
        (1, 'Admin'),  # an admin with all the perms
        (2, 'Just a user'),  # the user who has not bought premium sub
        (3, 'Premium')  # the user who indeed has bought the premium
    )

    userTelegramId = models.IntegerField('Телеграм айди', unique=True)
    userTelegramNickname = models.CharField('Имя пользователя', max_length=50)
    userStatus = models.IntegerField('Статус', editable=True, choices=userStatuses, default=2)
    userBalance = models.DecimalField('Баланс', max_digits=6, decimal_places=0, default=0, help_text='сумма в рублях')
    userPromo = models.CharField('Личный промокод', max_length=10, editable=False, unique=True, default=str(Promo(10)))
    activatedPromo = models.CharField('Активированный промокод', max_length=10, default='No promo')
    # --------------вот так вот наверное это должно выглядеть как-то-------------
    # promocode = models.OneToOneField(PromocodeModel, verbose_name='Промокод', related_name='promo', on_delete=models.CASCADE)

    def __str__(self) -> str:
        return f'Пользователь {self.userTelegramNickname}'

class PromocodeModel(models.Model):
    promo = models.CharField('Промокод', max_length=10, unique=True)
    usesCount = models.IntegerField('Использован(раз)', choices=[(i, i) for i in range(0, 6)], default=0)

And just in case, the user creation view.
class UserCreateView(APIView):
    def post(self, request) -> Response:
        user = UserCreateSerializer(data=request.data)

        if not user.is_valid():
            return Response({'Error': 'User was not created.', 'status': 0}, status=403)

        user.save()

        return Response(user.data, status=201)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-04-05
@AlexNest

1. Foreign keys should be done from "subordinate" to "master" i.e. since the promo code belongs to the user around whom the system is built, then the key must be made in the PromocodeModel.
2. It is not clear what the Promo function does in default=str(Promo(10))

When creating this user object, how can I also create a Promotional Code object, and write this promotional code in the pane from the user fields?

3. Why inflate the database with extra data fields? Does the duplicated promotional code carry any semantic load besides the fact that you do not need to add a search in a separate table? Not? Then feel free to delete one of the storage locations, because. it's data redundancy.
4. How to create?
If you left the field in the user model, then just generate it "by default" (I'll assume that's what I did) In the case of a separate model, just create a new object as usualdefault=str(Promo(10)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question