简体   繁体   中英

Unable to save null to ForeignKey in an intermediate model - Django

My use case is, there is a Workshop and there are multiple positions ( Workshop_Position ) in it. For any position there will be multiple applications. The workshop owner has to approve an application for the user to be a team_member in the workshop.

I am using a ManyToMany relationship for this, see below my models.

class Workshop(models.Model):
    ...
    team_members = models.ManyToManyField(settings.AUTH_USER_MODEL,  related_name='member_in_workshops', through='Membership')
   ...

class Workshop_Position(models.Model):
    position_heading = models.CharField(max_length=100, null=False, blank=False)
    ...

class Membership(models.Model): 
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='membership', blank=True, null=True, on_delete=models.CASCADE)
    position = models.ForeignKey('Workshop_Position', related_name='membership', on_delete=models.CASCADE)
    workshop = models.ForeignKey('Workshop', related_name='membership', on_delete=models.CASCADE)
    date_joined = models.DateTimeField(auto_now_add=True)

    class Meta:
       unique_together = ("position", "user")

So when a new position is created, I am saving the position to the Workshop_Position table and attempting to save the workshop the position belongs to with a null user into the Membership . I need to save this with a null user because there are going to be multiple applications to a Workshop_Position and the owner selects which user gets into the position. I am doing the below,

{
    "user": " ",
    "position": "3",
    "workshop": "1"
}

Please find below my MembershipSerializer

class MembershipSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset = UserProfile.objects.all(), allow_null=True)
    position = serializers.PrimaryKeyRelatedField(queryset = Workshop_Position.objects.all())
    workshop = serializers.PrimaryKeyRelatedField(queryset = Workshop.objects.all())

    class Meta:        
        model = Membership
        extra_kwargs = {
            'user': {'required': False, 'allow_null': True}
        }
        fields = ('id', 'user', 'position', 'workshop', 'date_joined')

But I get an error when I try to save the above to the Membership model.

"user": [ "This field may not be null." ]

Why do I get this error? I have provided the user within Membership model to have blank=True, null=True

Can someone please help me with this.

Thanks!

Are you using DRF ModelSerializer? In that case you'll need to declare this in your Serializer Class Meta.

class MembershipSerializer(serializers.ModelSerializer):
    class Meta:
        model = Membership
        extra_kwargs = {
            'user': {'required': False, 'allow_null': True}   # the allow_null might not be needed
        }

EDIT

I checked the DRF docs for PrimaryKeyRelatedField . As you can see there is something like this.

allow_null - If set to True, the field will accept values of None or the empty string for nullable relationships. Defaults to False.

So you'd need to change all your PrimaryKeyRelatedField like this.

serializers.PrimaryKeyRelatedField(queryset=your_queryset, allow_null=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM