Fetch user details from another model - django

I have a model(Poll) which contains another model(User) with user details.
I want to get the Username of who posted a poll
but the below is error occurred
I/flutter (21892): type 'int' is not a subtype of type 'String'
this is my model class(flutter)
import 'dart:convert';
class Poll {
Poll({
required this.id,
required this.choices,
required this.question,
required this.pubDate,
required this.createdBy,
});
late final int id;
late final List<Choices> choices;
late final String question;
late final String pubDate;
late final User createdBy;
Poll.fromJson(Map<String, dynamic> json) {
id = json['id'];
choices =
List.from(json['choices']).map((e) => Choices.fromJson(e)).toList();
question = json['question'];
pubDate = json['pub_date'];
createdBy = User.fromJson(jsonDecode(json['created_by']));
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['choices'] = choices.map((e) => e.toJson()).toList();
_data['question'] = question;
_data['pub_date'] = pubDate;
_data['created_by'] = createdBy.toJson();
return _data;
}
}
class Choices {
Choices({
required this.id,
required this.choiceText,
required this.poll,
});
late final int id;
late final String choiceText;
late final int poll;
Choices.fromJson(Map<String, dynamic> json) {
id = json['id'];
choiceText = json['choice_text'];
poll = json['poll'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['choice_text'] = choiceText;
_data['poll'] = poll;
return _data;
}
}
class User {
User({
required this.id,
required this.password,
required this.lastLogin,
required this.isSuperuser,
required this.username,
required this.firstName,
required this.lastName,
required this.email,
required this.isStaff,
required this.isActive,
required this.dateJoined,
required this.groups,
required this.userPermissions,
});
late final int id;
late final String password;
late final String lastLogin;
late final bool isSuperuser;
late final String username;
late final String firstName;
late final String lastName;
late final String email;
late final bool isStaff;
late final bool isActive;
late final String dateJoined;
late final List<dynamic> groups;
late final List<dynamic> userPermissions;
User.fromJson(Map<String, dynamic> json) {
id = json['id'];
password = json['password'];
lastLogin = json['last_login'];
isSuperuser = json['is_superuser'];
username = json['username'];
firstName = json['first_name'];
lastName = json['last_name'];
email = json['email'];
isStaff = json['is_staff'];
isActive = json['is_active'];
dateJoined = json['date_joined'];
groups = List.castFrom<dynamic, dynamic>(json['groups']);
userPermissions = List.castFrom<dynamic, dynamic>(json['user_permissions']);
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['id'] = id;
_data['password'] = password;
_data['last_login'] = lastLogin;
_data['is_superuser'] = isSuperuser;
_data['username'] = username;
_data['first_name'] = firstName;
_data['last_name'] = lastName;
_data['email'] = email;
_data['is_staff'] = isStaff;
_data['is_active'] = isActive;
_data['date_joined'] = dateJoined;
_data['groups'] = groups;
_data['user_permissions'] = userPermissions;
return _data;
}
}
here is how I am parsing the json
List<Poll> _polls = [];
Future<bool> getOffers() async {
var url = Uri.parse(polls_uri);
try {
http.Response response = await http.get(url);
var data = json.decode(response.body);
List<Poll> temp = [];
for (var element in data) {
Poll poll = Poll.fromJson(element);
temp.add(poll);
}
_polls = temp;
return true;
} catch (e) {
print(e);
return false;
}
}
List<Poll> get polls {
return [..._polls];
}
this is where i want to display I want to display the details
ListView.builder(
itemCount: polls.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Padding(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(polls[index].question),
Text(polls[index].createdBy.username),
]),
),
);
},
),
my model class(django)
class Poll(models.Model):
question = models.CharField(max_length=100)
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
pub_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.question
serializer
class PollSerializer(serializers.ModelSerializer):
choices = ChoiceSerializer(many=True, read_only=True, required = False)
class Meta:
model = Poll
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
views
class PollList(generics.ListCreateAPIView):
queryset = Poll.objects.all() [:20]
serializer_class = PollSerializer
Poll Json data: the key "created_by" is a model of class user... It is from the class I want to get the username
{
"id": 3,
"choices": [
{
"id": 9,
"choice_text": "Day",
"poll": 3
},
{
"id": 10,
"choice_text": "Boarding",
"poll": 3
},
{
"id": 11,
"choice_text": "Mixed",
"poll": 3
}
],
"created_by": 1,
"question": "Type of School: Day or Boarding",
"pub_date": "2022-07-21T13:29:23.445097Z"
},

Related

Accessing a nested list of objects in dart

I have a list of Care requirements name care requirements list which consist of requirement_id, requirement_name and care_levels_list which is inside the care requirements list.The care requirements list is retrieved through an API response and is in the format
[CareRequirement(1, Requirement 1, [{care_level_id: 1, care_level_name: no-help, price: 2000.00}, {care_level_id: 2, care_level_name: supervise, price: 1000.00}, {care_level_id: 3, care_level_name: assist, price: 1000.00}]), CareRequirement(2, Requirement 2, [{care_level_id: 2, care_level_name: supervise, price: 3000.00}]),
how can I access the price of the care level id 1 of requirement 1?
CareRquirement model
class CareRequirement extends Equatable {
int id = 0;
String name = '';
List careLevelsList = [];
CareRequirement(
{required this.id, required this.name, required this.careLevelsList});
#override
List<Object?> get props => [id, name, careLevelsList];
#override
CareRequirement.fromJson(Map<String, dynamic> json) {
id = json['id'];
name = json['name'];
careLevelsList = json['care_levels'];
}
Map toJson() {
Map jsonData = {
"id": id,
"name": name,
"care_levels": careLevelsList,
};
return jsonData;
}
static pure() {
return CareRequirement(
id: 0,
name: '',
careLevelsList: [],
);
}
}

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'List<String>': Flutter

// i am having error in the line: _picture = snapshot.data()[PICTURE]; , it is returning the unhandled exception. type 'List' is not a subtype of type 'List' This is the image of my firebase
import 'package:cloud_firestore/cloud_firestore.dart';
class ProductModel {
static const ID = "id";
static const NAME = "name";
static const PICTURE = "picture";
static const PRICE = "price";
static const DESCRIPTION = "description";
static const CATEGORY = "category";
static const QUANTITY = "quantity";
static const BRAND = "brand";
static const PAYSTACK_ID = "paystackId";
String _id;
String _name;
List<String> _picture;
String _description;
String _category;
String _brand;
int _quantity;
int _price;
String _paystackId;
String get id => _id;
String get name => _name;
List<String> get picture => _picture;
String get brand => _brand;
String get category => _category;
String get description => _description;
int get quantity => _quantity;
int get price => _price;
String get paystackId => _paystackId;
ProductModel.fromSnapshot(DocumentSnapshot snapshot) {
_id = snapshot.data()[ID];
_brand = snapshot.data()[BRAND];
_description = snapshot.data()[DESCRIPTION] ?? " ";
_price = snapshot.data()[PRICE].floor();
_category = snapshot.data()[CATEGORY];
_name = snapshot.data()[NAME];
_picture = snapshot.data()[PICTURE];
_paystackId = snapshot.data()[PAYSTACK_ID] ;
}
}
//Also the second error detected is coming from line: products.add(ProductModel.fromSnapshot(product)); both are throwing unhandled exception type 'List' is not a subtype of type 'List'
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:farmers_ecommerce/models/product.dart';
class ProductServices {
String collection = "products";
FirebaseFirestore _firestore = FirebaseFirestore.instance;
Future<List<ProductModel>> getProducts() async {
QuerySnapshot result= await _firestore.collection(collection).get();
List<ProductModel> products = [];
for (DocumentSnapshot product in result.docs) {
products.add(ProductModel.fromSnapshot(product));
}
return products;
}
Future<List<ProductModel>> searchProducts({String productName}) {
// code to convert the first character to uppercase
String searchKey = productName[0].toUpperCase() + productName.substring(1);
return _firestore
.collection(collection)
.orderBy("name")
.startAt([searchKey])
.endAt([searchKey + '\uf8ff'])
.get()
.then((result) {
List<ProductModel> products = [];
for (DocumentSnapshot product in result.docs) {
products.add(ProductModel.fromSnapshot(product));
}
return products;
});
}
}
It worked when i changed List <String> to List<dynamic>. Basically, this enabled to automatically scan through the different images associated to the 'picture' collection.

Flutter - Fill future list from json

I want to fill a list from json.
Future<List<Titles>> fetchTitle() async {
String url = "https://jsonplaceholder.typicode.com/posts";
final response = await http.get(url,headers: {'Content-Type': 'application/json'});
return titlesFromJson(utf8.decode(response.bodyBytes));
How to fill below list using fetchTitle method. I want to add "title" item from json.
final List myLists = [];
Expanded(
child: GridView.count(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
childAspectRatio: 1,
padding: EdgeInsets.only(left: 20, top: 20, right: 20),
children:List.generate(myLists.length, (index) {
return InkWell(
From the official documentation this is the way on how to fetch data from json and convert the response to list of model:
1- create a model for the post
class Post {
int userId;
int id;
String title;
String body;
Post({this.userId, this.id, this.title, this.body});
Post.fromJson(Map<String, dynamic> json) {
userId = json['userId'];
id = json['id'];
title = json['title'];
body = json['body'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['userId'] = this.userId;
data['id'] = this.id;
data['title'] = this.title;
data['body'] = this.body;
return data;
}
}
2 - import http package and fetch post from the link https://jsonplaceholder.typicode.com/posts
import 'package:http/http.dart' as http;
Future<List<Post>> fetchPosts(http.Client client) async {
final response = await client
.get('https://jsonplaceholder.typicode.com/posts');
return parsePosts(response.body);
}
3 - Use the method that you define on your model to create a list that contain posts
import 'dart:convert';
List<Post> parsePosts(String responseBody) {
final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Post>((json) => Post.fromJson(json)).toList();
}
4 - to make a test that your code work, create a simple async main method that call fetchPosts with the await prefix because fetchPosts return a Future so if you don't use await you will get a future and not the List
void main() async {
List posts = await fetchPosts(http.Client());
// this will print the id and the title of posts
posts.forEach((post) => print('Post id: ${post.id} | Post title: ${post.title}'));
}
I hope this help!
To add the JSON result to a list, you may need to wait for the response and add it to the List. Since fetchTitle() method returns Future<List<Titles>>, when you await for it, you will get a List<Titles> which can be assigned to your myList.
myList = await fetchTitle();
Since we are using await, we may need to mark the method using async keyword.
void main() async {
List myList = [];
myList = await fetchTitle();
print(myList);
}

Joining 2 lists with condition

I want to join 2 lists. Students and Persons.
Both Student and Person has id and a name variable, plus Student has another variable called isStudying. I want to join all Students to Person with the isStudying variable.
var persons = new Person { id = 1, name = "John" };
var persons = new Person { id = 2, name = "Ace" };
var persons = new Person { id = 3, name = "Mike" };
var persons = new Person { id = 4, name = "Yob" };
var persons = new Person { id = 5, name = "Ken" };
var students = new Student { id = 2, name = "Ace", isStudying=true };
var students = new Student { id = 3, name = "Mike", isStudying = true };
var students = new Student { id = 5, name = "Ken", isStudying = true };
persons.Addrange(students.where(student.id.contain(persons.id)));
Here is full solution implemented in linq, used inheritance
class Person
{
public int id { get; set; }
public string name { get; set; }
}
class Student : Person
{
public bool isStudying { get; set; }
}
void Main()
{
var person1 = new Person { id = 1, name = "John" };
var person2 = new Person { id = 2, name = "Ace" };
var person3 = new Person { id = 3, name = "Mike" };
var person4 = new Person { id = 4, name = "Yob" };
var person5 = new Person { id = 5, name = "Ken" };
var persons = new List<Person> { person1, person2, person3, person4, person5 };
var student1 = new Student { id = 2, name = "Ace", isStudying = true };
var student2 = new Student { id = 3, name = "Mike", isStudying = true };
var student3 = new Student { id = 5, name = "Ken", isStudying = true };
var students = new List<Student> { student1, student2, student3 };
var personsRes = persons.Where(y => students.Select(x => x.id).Contains(y.id));
Console.WriteLine(personsRes);
}
Try This:
public class Person
{
public int id { get; set; }
public string name { get; set; }
}
public class Student
{
public int id { get; set; }
public string name { get; set; }
public bool isStudying { get; set; }
}
var persons = new List<Person> { new Person { id = 1, name = "John" },
new Person { id = 2, name = "Ace" },
new Person { id = 3, name = "Mike"},
new Person { id = 4, name = "Yob" },
new Person { id = 5, name = "Ken" } };
var students = new List<Student> { new Student { id = 2, name = "Ace", isStudying = true },
new Student { id = 3, name = "Mike", isStudying = true },
new Student { id = 5, name = "Ken", isStudying = true } };
var allPersons = (from p in persons
join s in students on new { first = p.id } equals new { first = s.id } into sjoin
from slj in sjoin.DefaultIfEmpty()
select new
{
id = p.id,
name = p.name,
isStudying = (slj != null ? (slj.isStudying ? "TRUE" : "FALSE") : string.Empty)
}).ToList();
For future readers' reference, one simple answer which I provided in comments using LINQ is:
With anonymous types:
persons.Select(p => new { p.id, p.name, students.Any(s => s.id == p.id && s.isStudying) });
Using a custom class (the Student class can actually be re-used):
persons.Select(p => new Student { id = p.id, name = p.name, isStudying = students.Any(s => s.id == p.id && s.isStudying) });

Display certain list when clicking on different links in a view

I need to display a different list each time I click on different links in my view. Help would be appreciated :)
My controller:
public class HomeController : Controller
{
Teams tm = new Teams();
Details det = new Details();
public ActionResult Index()
{
var model = new List<Teams>();
model.Add(new Teams { Name = "Manchester United", NickName = "The Red Devils", HomeGround = "Old Trafford", Founded = 1878 });
model.Add(new Teams { Name = "Liverpool", NickName = "The reds", HomeGround = "Anfield", Founded = 1870 });
return View(model);
}
public ActionResult About()
{
var title = new List<Details>();
title.Add(new Details { MajorHonours = 62, PremLeague = 20, FACup = 11, LeagueCup = 4, UEFA = 3 });
title.Add(new Details { MajorHonours = 60, PremLeague = 18, FACup = 7, LeagueCup = 8, UEFA = 5 });
return View();
}
My view with the links:
#model IEnumerable<Standings.Models.Teams>
#{
ViewBag.Title = "Standings";
}
<h1>List of teams</h1>
#foreach (var item in Model)
{
<div>
#Html.ActionLink(#item.Name, "About") (#item.NickName, #item.HomeGround, #item.Founded)
<hr />
</div>
}
My model:
public class Details
{
public int MajorHonours { get; set; }
public int PremLeague { get; set; }
public int FACup { get; set; }
public int LeagueCup { get; set; }
public int UEFA { get; set; }
}
And I have a clean View with the name About that the list needs to be displayed on