I want to to get the username of a user from another model, I have two tables(users and notes) in my database which are related to each other
but I'm getting this exception error
Exception has occurred.
FormatException (FormatException: Unexpected character (at character 1)
f1c84842-e146-4936-9659-e4872c012240
^
)
below is the json generated for both tables: users
[
{
"id": "f1c84842-e146-4936-9659-e4872c012240",
"username": "admin",
"password": "pbkdf2_sha256$320000$Zt8E5evRtqUS1GEdkFhj7l$3K0fL4oKonJJluJQaYC749RhjhwFOmv YGce0ajWuYY=",
"email": "[email protected]"
}
]
notes
[
{
"id": 1,
"body": "debugging",
"updated": "2022-07-24T03:39:57.188340Z",
"created": "2022-07-24T03:39:57.188340Z",
"user": "f1c84842-e146-4936-9659-e4872c012240"
}
]
here is my model from the database
class CustomUser(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(unique=True)
class Note(models.Model):
user = models.ForeignKey(CustomUser, null=True, on_delete=models.CASCADE)
body = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body[0:50]
class Meta:
ordering = ['-updated']
below is my model class on flutter
List<Note> noteFromJson(String str) =>
List<Note>.from(json.decode(str).map((x) => Note.fromJson(x)));
String noteToJson(List<Note> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class Note {
Note({
this.id,
required this.body,
this.updated,
this.created,
required this.user,
});
int? id;
String body;
DateTime? updated;
DateTime? created;
User user;
factory Note.fromJson(Map<String, dynamic> json) => Note(
id: json["id"],
body: json["body"] as String,
updated: DateTime.parse(json["updated"]),
created: DateTime.parse(json["created"]),
user: User.fromJson(jsonDecode(json["user"])),
);
Map<String, dynamic> toJson() => {
"id": id,
"body": body,
"updated": updated?.toIso8601String(),
"created": created?.toIso8601String(),
"user": user.toJson()
};
}
List<User> userFromJson(String str) =>
List<User>.from(json.decode(str).map((x) => User.fromJson(x)));
String userToJson(List<User> data) =>
json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class User {
User({
required this.id,
required this.username,
this.password,
required this.email,
});
String id;
String username;
String? password;
String email;
factory User.fromJson(Map<String, dynamic> json) => User(
id: json["id"],
username: json["username"],
password: json["password"],
email: json["email"],
);
Map<String, dynamic> toJson() => {
"id": id,
"username": username,
"password": password,
"email": email,
};
}
and here is how i am parsing the json:
Client client = http.Client();
class RemoteServices {
Future<List<Note>?> getNotes() async {
var client = http.Client();
var response = await client.get(retrieveUrl);
//if data is retrieved
if (response.statusCode == 200) {
var json = response.body;
final note = noteFromJson(json);
return note;
}
}
}
List<Note>? notes;
bool isLoaded = false;
@override
void initState() {
getData();
super.initState();
}
getData() async {
notes = await RemoteServices().getNotes();
print(notes);
if (notes != null) {
print(notes);
setState(() {
print(notes);
isLoaded = true;
});
}
}
update:
the below is response.body
Restarted application in 4,768ms.
I/flutter (12188): [{"id":1,"body":"debugging","updated":"2022-07-24T03:39:57.188340Z","created":"2022-07-24T03:39:57.188340Z","user":"f1c84842-e146-4936-9659-e4872c012240"}]
New update:
my views
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class NoteList(generics.ListCreateAPIView):
queryset = Note.objects.all()
serializer_class = NoteSerializer
serializers
class NoteSerializer(ModelSerializer):
class Meta:
model = Note
fields = '__all__'
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ['username', 'password', 'email']
CodePudding user response:
replace
class NoteSerializer(ModelSerializer):
class Meta:
model = Note
fields = '__all__'
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ['username', 'password', 'email']
to
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ['username', 'password', 'email']
class NoteSerializer(ModelSerializer):
user = UserSerializer()
class Meta:
model = Note
fields = '__all__'
and test