'How to get(access) foreign key's member instance in django?
articles/models.py
class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)user/models.py
class User(AbstractUser): username = models.CharField(max_length=20) email = models.EmailField(_('email address'), unique=True) profile_image_url = models.TextField()
Is there any other way to include or access user's member instance (username, email, profile_image_url) into class Article??
I'd like to make class Article into this
class Article(models.Model):
User.username
User.email
User.profile_image_url
FYI,my Serializer are these
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = ['emotion', 'location', 'menu', 'weather', 'song', 'point', 'content', 'image', 'user', 'created', 'liked', 'num_liked']
class UsersSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'date_joined', 'email', 'profile_image_url',
'followings', 'followers')
Is there any other way to make my ArticleSerializer to include UserSerializer's fields? or Is there any other way to include or access user's member instance (username, email, profile_image_url) into class Article??
Solution 1:[1]
You could try this:
class ArticleSerializer(serializers.ModelSerializer):
email = serializers.CharField(source='user.email', allow_null=True)
# And so on
class Meta:
model = Article
fields = ('id', 'user', 'email')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Karim Bourahla |
