问题
Once the system detects that you already invited 2 users, your profile will automatically save in graduate list
please see this picture, as example:
this is the table of graduate list.
as you can see in the picture, Joe Dio has already invited 2 users (miro and justin), (you can see it in the Sponsor user)
I hope you can help me to figure it out using django signal, thanks in advance :)
i wish the example I made had you understood what i wanted to get
this is my models.py
class User(models.Model):
firstname = models.CharField(max_length=500, null=True,blank=True)
lastname = models.CharField(max_length=500, null=True, blank=True)
middlename = models.CharField(max_length=500, null=True, blank=True)
birthday = models.CharField(max_length=500, null=True, blank=True)
Email = models.CharField(max_length=500,null=True,blank=True)
Sponsor_User = models.ForeignKey('self', on_delete=models.CASCADE,blank=True, null=True)
class User_GraduateList(models.Model):
User = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE, blank=True)
def __str__(self):
suser = '{0.User}'
UPDATE this is the answer of mr @AKS
class User_GraduateList(models.Model):
User = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE, blank=True)
@receiver(post_save, sender=User)
def create_graduates(sender, instance, created, **kwargs):
sponsor = instance.Sponsor_User
if created and sponsor:
if sponsor.user_set.count() >= 2:
if not User_GraduateList.objects.filter(User=sponsor).exists():
User_GraduateList.objects.create(User=sponsor)
it didnt work.
回答1:
class User_GraduateList(models.Model):
User = models.ForeignKey(User, related_name='+', on_delete=models.CASCADE, blank=True)
@receiver(post_save, sender=User)
def create_graduates(sender, instance, created, **kwargs):
sponsor = instance.Sponsor_User
if created and sponsor:
if sponsor.user_set.count() >= 2:
if not User_GraduateList.objects.filter(User=sponsor).exists():
User_GraduateList.objects.create(User=sponsor)
For reading purposes, I have nested the if conditions. If you feel comfortable, you can join then using and.
The solution above is based on the assumption that we only want to do this when a new user is created. If the sponsor user can be set later, the created check can be removed from the first condition.
Also, looking at the models, I think it will be best to have a one to one relationship between the User_GraduateList and User model.
来源:https://stackoverflow.com/questions/60559305/django-signal-post-save