0

I'm having two models where UserGroup model, which contains a group admin, and DetailedUser model which related to the group model, where the field user points all users in the certain UserGroup, I want to add a field that when a new user added to the group it store its date and time of user added to the particular group.

class UserGroup(models.Model):
    group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_by')
    group_name = models.CharField(max_length=100)
    group_amount = models.PositiveSmallIntegerField()

    def __str__(self):
        return self.group_name

class DetailedUser(models.Model):
    group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, related_name='user_group')
    user = models.ManyToManyField(
        User, related_name='single_user')
    user_added = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    
    def __str__(self):
        return f"{self.group.group_name}"

How can I done this method?

1 Answer 1

1

I think your model design is not correct. What you need(I think) is ManyToManyField with though. For example:

class UserGroup(models.Model):
    group_admin = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_by')
    group_name = models.CharField(max_length=100)
    group_amount = models.PositiveSmallIntegerField()
    members = models.ManyToManyField(User, through="DetailedUser")

    def __str__(self):
        return self.group_name

class DetailedUser(models.Model):
    group = models.ForeignKey(UserGroup, on_delete=models.CASCADE, related_name='user_group')
    user = models.ForeignKey(
        User, related_name='single_user')
    user_added = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    
    def __str__(self):
        return f"{self.group.group_name}"

Usage example:

>> group = UserGroup.objects.get(pk=1)
>> user = User.objects.first()
>> DetailedUser.objects.create(group=group, user=user)
>> group.memebers.all()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.